In this video tutorial lets learn about preprocessor command or directives like #ifdef, #else and #endif. These directives are used for conditional compilation.
Page Contents
The block of code between #ifdef and #endif works only if the macro name is defined orelse the compiler will skip the entire block of code from compiling.
1. When we want the compiler to skip certain part of the source code: For this we could even use multi-line comment, but if we already had multi-line comments in the code, we can’t enclose the source code and multi-line comments with another multi-line comment. Nesting of multi-line comments are not allowed in C programming language. So instead of commenting the code we could make use of #ifdef directive.
2. To write portable code: For example, we could write code both for iOS and non-iOS devices. Using #ifdef we could check the device OS and based on that deliver specific set of codes. For this we can use #ifdef
#include<stdio.h> #define iOS int main() { #ifdef iOS printf("This is iOS Code\n"); #else printf("This is code for Android Devices\n"); #endif // iOS return 0; }
Output:
This is iOS Code
#include<stdio.h> int main() { #ifdef iOS printf("This is iOS Code\n"); #else printf("This is code for Android Devices\n"); #endif // iOS return 0; }
Output:
This is code for Android Devices
In above programs, if iOS macro name is defined, then the set of code present inside #ifdef block gets compiled and executed. If macro name iOS is not defined, then the code inside #else block gets compiled and executed.
#include<stdio.h> #define iOS int main() { #ifdef iOS printf("This is iOS Code\n"); #endif // iOS printf("This is code for all non iOS Devices\n"); return 0; }
Output:
This is iOS Code
This is code for all non iOS Devices
#include<stdio.h> int main() { #ifdef iOS printf("This is iOS Code\n"); #endif // iOS printf("This is code for all non iOS Devices\n"); return 0; }
Output:
This is code for all non iOS Devices
Note: using #else is optional. You can just use #ifdef and #endif.
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