In this video tutorial lets learn about preprocessor command or directives like #ifndef, #else and #endif. These directives are used for conditional compilation. #ifndef works completely opposite to #ifdef
Related Read:
Conditional Compilation In C: #ifdef #else #endif
Page Contents
The block of code between #ifndef and #endif works only if the macro name is NOT defined. If the macro name is defined, the compiler will skip the entire block of code inside #ifndef from compiling.
We’ve explained this in detail for video tutorial: Conditional Compilation In C: #ifdef #else #endif It holds good for this video tutorial too.
#include<stdio.h> #define iOS int main() { #ifndef iOS printf("I Love Apple Devices\n"); #else printf("Code for Non Apple Devices\n"); #endif // iOS return 0; }
Output:
Code for Non Apple Devices
#include<stdio.h> int main() { #ifndef iOS printf("I Love Apple Devices\n"); #else printf("Code for Non Apple Devices\n"); #endif // iOS return 0; }
Output:
I Love Apple Devices
In above programs, if iOS macro name is defined, then the set of code present inside #else block gets compiled and executed. If macro name iOS is not defined, then the code inside #ifndef block gets compiled and executed.
Note:
1. Using #else is optional. You can just use #ifndef and #endif.
2. Working of #ifndef is opposite to that of #ifdef.
3. This is similar to if else condition, but here the block of code which do not match the criteria doesn’t even get compiled. It’s treated like regular comments.
For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List
For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert