C/C++ Programmer's Guide (G06.25+)
Preprocessor Directives and Macros
HP C/C++ Programmer’s Guide for NonStop Servers—429301-002
12-6
#if, #elif, #ifdef, #ifndef, #else, and #endif
#endif newline
terminates the if section. The new line following the #endif directive terminates
the directive line.
Usage Guidelines
•
When using the if directives, remember to distinguish between macro definitions
and function definitions; the #ifdef and #ifndef directives test only macro
definitions.
•
The preprocessor selects a single source-text evaluating the constant
expression following each #if or #elif directive until it finds a true, nonzero,
constant-expression. It selects all text up to its associated #elif, #else, or
#endif.
•
If all occurrences of constant-expression are false, or if no #elif directives
appear, the preprocessor selects the source text after the #else clause. If the
#else clause is omitted and all instances of constant-expression in the #if
blocks are false, no source text is selected.
Examples
1. This example shows how the #if, #else, and #endif directives interact.
Because the identifier ANSI is defined as zero (false), the #if test fails. As a
result, the compiler processes only the source text in the else group:
#define ANSI 0
#if ANSI
printf("Function prototypes supported.\n");
#else
printf("Function prototypes not supported.\n");
#endif
2. This example shows how the #elif directive works. The #if, #elif, and #else
directives are used to make one of three choices, based on the value of XCOORD
and YCOORD. Note that XCOORD and YCOORD must be defined constants.
#define XCOORD 5
#define YCOORD 5
#if XCOORD == 10
printf("Intersection at (10,5).\n");
#elif YCOORD == 10
printf("Intersection at (5,10).\n");
#else
printf("Intersection at (5,5) \n");
#endif
3. This example shows how the #ifdef directive works. Because PC is defined as a
macro, the compiler processes the source text following the #ifdef PC directive.