These are used for conditional compilation, to control which sections of code are compiled.
Example
#if constant_expression /* If constant_expression is non-zero, compile this */ #else /* otherwise compile this */ #endif /* Need this to mark the end of the conditional section */
You can also use #if...#endif without the #else.
The #ifdef is slightly different: you test with
#ifdef identifier
and if the identifier is currently #defined, then the if-block is compiled. #ifndef has the same effect if the identifier is not defined. Both can have #else and both must end with #endif. There is an important debugging use of this facility. Consider:
#ifdef DEBUG
printf("Have reached position X in the program\n");
#endif
Normally this print statement will not be compiled. We could force it to compile with a #define but this is such a valuable use that the compiler has a switch (-D) to define any identifier directly:
cc -DDEBUG my_prog.c
causes DEBUG to be defined, and therefore forces the compilation of the ``print'' statement.
The variant:
cc -DDEBUG=10 my_prog.c
is the same as having
#define DEBUG 10
in your program. The first version is equivalent to:
#define DEBUG 1
You can narrow down the range of debugging by appropriate use of #undef.
maspjw@