The #ifdef, #ifndef, #elseif, #elif, #else, and #endif are the logical directives of the preprocessor. These logical operations determine the fate of information processed the preprocessor. The syntax of the conditional directives are: #ifdef Name0 lines to evaluate if Name0 is defined #elseif Name1 lines to evaluate if Name1 is defined, and Name0 is Not defined ... #elif NameN lines to evaluate if NameN is defined, and Name0-Name(N-1) is Not defined #else lines to evaluate if Name0-NameN are Not defined #endif
and
#ifndef Name0 lines to evaluate if Name0 is Not defined #elseif Name1 lines to evaluate if Name1 is defined, and Name0 is defined #else lines to evaluate if Name0 is defined and Name1 is Not defined #endif
The expression #ifdef Name evaluates to true in Name has been #defined. In this case (true), the input file lines are processed until a #elseif, #else, or #endif directive is encountered. The #elseif, #else, and #endif directives are valid only following a #ifdef directive. If the #ifdef directive evaluated to be true, t hen these directives (#elseif, #else, and #endif) stop processing of the input lines until a #endif directive is encounter. Thus, the code
/* simple_ifdef.inp */ #define TEST1 #define TEST2 #ifdef TEST1 test1 is defined, test2 and test3 are unchecked #elseif TEST2 test1 is not defined, test2 is defined, test3 is unchecked #elseif TEST3 test1 and test2 are not defined, test3 is defined #else test1, test2, test3 are not defined. #endif /* check for TEST2 alone */ #ifdef TEST2 test2 is defined #endifevaluates to be
test1 is defined, test2 and test3 are unchecked test2 is defined
If an #ifdef is evaluated to be false, then the #elseif directive is processed as if it was an #ifdef directive. If all #elseif directives evaluate to be false, the #else directive is processed if it exists. Input is evaluated until an #endif directive is encountered. A #endif directive ends the #ifdef processing.
#ifdef directives can be nested, however, all directives in a given logical level must exist in a single file.
The following sample code showing use of the #ifdef directive chain with nested #ifdefs.
/* ifdef_example.inp */ #define TEST1 100 // define a variable. #define TEST2 /* process the input based on the what was defined above */ #ifdef TEST1 TEST1 (test1) is defined #ifdef TEST2 // another check (nested within the first) The Value TEST2 (test2) is defined #else // else for #ifdef TEST2 TEST1 (test1) is defined and TEST2 is not defined #endif // #endif for #ifdef TEST2 #elseif TEST2 TEST1 is NOT Defined, and TEST2 (test2) is defined #else TEST1 and TEST2 are not defined #endifIt evaluates to be equal to
100 (test1) is defined The Value TEST2_DEFINED_WITHOUT_A_VALUE (test2) is defined
The expression #ifndef Name evaluates to true in Name has not been #defined. Processing continues similar to an ifdef directive.
The #elif is functionally equivalent to the #elseif directive. These directives are interchangeable.