Home > Electronics Tutorials > C Language Tutorial > Preprocessing Directives - #if, #elif, #else, #endif

C Language Programming Library Reference Guide

Preprocessing Directives - #if, #elif, #else, #endif

These preprocessing directives create conditional compiling parameters that control the compiling of the source code. They must begin on a separate line.

Syntax:
 

#if constant_expression
#else
#endif

or

#if
constant_expression
#elif constant_expression
#endif
  The compiler only compiles the code after the #if expression if the constant_expression evaluates to a non-zero value (true). If the value is 0 (false), then the compiler skips the lines until the next #else, #elif, or #endif. If there is a matching #else, and the constant_expression evaluated to 0 (false), then the lines between the #else and the #endif are compiled. If there is a matching #elif, and the preceding #if evaluated to false, then the constant_expression after that is evaluated and the code between the #elif and the #endif is compiled only if this expression evaluates to a non-zero value (true).

Examples:

int main(void)
 {
  #if 1
    printf("Yabba Dabba Do!\n");
  #else
    printf("Zip-Bang!\n");
  #endif
  return 0;
}
Only "Yabba Dabba Do!" is printed.
int main(void)
 {
  #if 1
    printf("Checkpoint1\n");
  #elif 1
    printf("Checkpoint2\n");
  #endif
  return 0;
}
Only "Checkpoint1" is printed. Note that if the first line is #if 0, then only "Checkpoint2" would be printed.
#if OS==1
  printf("Version 1.0");
#elif OS==2
  printf("Version 2.0");
#else
  printf("Version unknown");
#endif
Prints according to the setting of OS which is defined with a #define.
Note: To report broken links or to submit your projects, tutorials please email to Webmaster

Discover

     more......