Show: Delphi C++
Display Preferences

#if, #elif, #else, and #endif (C++)

From RAD Studio
Jump to: navigation, search

Go Up to Conditional Compilation Directives (C++)


#if constant-expression-1
<#elif constant-expression-2 newline section-2>
<#elif constant-expression-n newline section-n>
<#else <newline> final-section>


The compiler supports conditional compilation by replacing the appropriate source-code lines with a blank line. The lines thus ignored are those lines that are not to be compiled as a result of the directives. All conditional compilation directives must be completed in the source or include file in which they are begun.

The conditional directives #if, #elif, #else, and #endif work like the normal C conditional operators. If the constant-expression-1 (subject to macro expansion) evaluates to nonzero (true), the lines of code (possibly empty) represented by section-1, whether preprocessor command lines or normal source lines, are preprocessed and, as appropriate, passed to the compiler. Otherwise, if constant-expression-1 evaluates to zero (false), section-1 is ignored (no macro expansion and no compilation).

In the true case, after section-1 has been preprocessed, control passes to the matching #endif (which ends this conditional sequence) and continues with next-section. In the false case, control passes to the next #elif line (if any) where constant-expression-2 is evaluated. If true, section-2 is processed, after which control moves on to the matching #endif. Otherwise, if constant-expression-2 is false, control passes to the next #elif, and so on, until either #else or #endif is reached. The optional #else is used as an alternative condition for which all previous tests have proved false. The #endif ends the conditional sequence.

The processed section can contain further conditional clauses, nested to any depth; each #if must be matched with a closing #endif.

The net result of the preceding scenario is that only one section (possibly empty) is passed on for further processing. The bypassed sections are relevant only for keeping track of any nested conditionals, so that each #if can be matched with its correct #endif.

The constant expressions to be tested must evaluate to a constant integral value.

See Also

Personal tools
RAD Studio 10.2 Tokyo
In other languages
Previous Versions