The C preprocessor supports conditional compilation via the #if directive. The
syntax of the #if directive is shown below.
if_part elif_parts else_part endif_line
elif_part elif_line text
#define A 1
#define B 2
#define C 3
#if !defined(A) || !defined(B)
#define D 4
#elif defined B && !defined C
#define E 5
#define F 6
In the above code fragment, the constant expression following the #if
directive evaluates to false as does the constant expression following the #elif
directive. Therefore the #else portion is executed, thereby causing the macro F to
be defined. Note that the macros D and E are not defined.
- During preprocessing, the constant expressions
following the #if and #elif directives are consecutively evaluated until one
is found to be true (i.e. non-zero). The source text following the first true
expression is included in the compilation (and the text enclosed by the
remaining #elif and #else directives is ignored). If none of the expressions
associated with the #if and #elif directives evaluates to true then if a #else directive
is present then the source text following it is included in the compilation.
If no #else directive is present and none of the expressions following the #if
and #elif directives evaluates to true then all text down to the #endif is excluded.
- The defined operator can be applied to test the existence of a
macro (as shown in the example above).
The two forms of the defined operator are defined identifier and
defined(identifier). The defined operator returns 1 if the named identifier
is a macro and 0 otherwise. Undefining an existing
macro causes the defined operator to subsequently return 0. The identifier defined
cannot itself be defined as a macro.
- After any defined operators have been evaluated,
macros found in an expression following a #if or #elif
directive are replaced. What remains is then evaluated as a
constant integral expression except that int and
unsigned int are treated as long and unsigned long respectively, and the
expression may not contain a sizeof operator, an
enumeration constant or a
- A directive of the form #ifdef identifier is equivalent to
- A directive of the form #ifndef identifier is equivalent to
- Condition compilation directives may be nested.