Name
#if directive — Tests a condition
Synopsis
#if constant-expression
The #if
directive begins a
region of conditional compilation, that is, a region within a source
file where preprocessor directives determine whether the code in the
region is compiled. A conditional region starts with #ifdef
, #ifndef
, or #if
and ends with #endif
. Each region can have any number of
#elif
directives and an optional
#else
directive after all the
#elif
directives. The basic form to
use is:
#if defined(_ _win32_ _) const char os[] = "Microsoft Windows"; #elif defined(__linux__) or defined(_ _unix_ _) const char os[] = "UNIX (or variant)"; #elif defined(_ _vms_ _) const char os[] = "VMS"; #else const char os[] = "(unknown)"; #endif
Macros in the directive argument are expanded, except for the
operands of the defined
operator.
The constant expression is evaluated, and if the result is nonzero,
the #if
condition is true, and the
code in the region that immediately follows is compiled. The region
ends with #else
, #elif
, or #endif
. If the #if
expression is false, the condition for
the next #elif
is evaluated, and if
that expression is true, its region is compiled, and so on. If all
#elif
expressions are false, and
#else
is present, its region is
compiled. Conditional processing ends with the corresponding #endif
directive.
Conditionals can be nested. Within an inner region, the preprocessor keeps track of conditional directives even if the region is not being compiled, so conditional directives can be properly ...
Get C++ In a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.