The #if and #elif directives

The #if directive conditionally includes text for preprocessing. If the condition that follows the #if directive evaluates to a nonzero value, the text following up to but excluding the associated #endif is included as preprocessing input.

The #elif (a contraction of else-if) directive, if used, must be contained within a section of text subject to an #if directive. This directive optionally includes a section of text based on the evaluation result of the condition that immediately follows the directive. The #elif directive evaluates its condition only when the original condition on the #if evaluates to false and all conditions associated with preceding #elif directives subject to the original #if also evaluate to false.

Read syntax diagramSkip visual syntax diagram
#if and #elif directive syntax

>>-#--+-if---+--constant_expression----------------------------><
      '-elif-'                        

All macros are expanded, except macros that are the operand of a defined operator. Any uses of the defined operator are processed, and all remaining keywords and identifiers are replaced with the token 0 C++ only beginsexcept true and falseC++ only ends.

The behavior is undefined if expanding the macros resulted in the token defined.

Notes:
  • Casts cannot be performed. For example, the following code can be compiled successfully by both the C and C++ compilers.
    #if static_cast<int>(1)
    #error Unexpected
    #endif
    
    int main() {
    }
  • Arithmetic is performed using long int type. C++11 In C++11, arithmetic is performed using long long int type. See C99 preprocessor features adopted in C++11 (C++11) for detailed information.C++11 ends
  • The constant_expression can contain defined macros.
  • The constant_expression can contain the unary operator defined. This operator can be used only with the preprocessor keyword #if or #elif. The following expressions evaluate to 1 if the identifier is defined in the preprocessor, otherwise to 0:
    defined identifier
    defined(identifier)
    For example:
    #if defined(TEST1) || defined(TEST2)
  • The constant_expression must be an integral constant expression.
If a macro is not defined, a value of 0 (zero) is assigned to it. In the following example, TEST is a macro identifier.
#include <stdio.h>
int main()
{
   #if TEST != 0    // No error even when TEST is not defined.
       printf("Macro TEST is defined to a non-zero value.");
   #endif
}