The #if directive specifies that certain statements are to be included only if the value represented by the conditional
expression is nonzero. The conditional expression can be an arithmetic expression.
The general form to use the #if directive is
#if expression
statement1
statement2
. . .
statementN
#endif
Here expression is the conditional expression to be evaluated. statement1, statement2, and statementN represent the
code to be included if expression is nonzero.
Note that the #endif directive is included at the end of the definition to mark the end of the #if block, as it does for an
#ifdef or #ifndef block.
In addition, the #else directive provides an alternative to choose. The following general form uses the #else directive
to put statement_1, statement_2, and statement_N into the program if expression is zero:
#if expression
statement1
statement2
. . .
statementN
#else
statement_1
statement_2
. . .
statement_N
#endif
Again, the #endif directive is used to mark the end of the #if block.
Also, a macro definition can be used as part of the conditional expression evaluated by the #if directive. If the macro
is defined, it has a nonzero value in the expression; otherwise, it has the value 0.
For example, look at the following portion of code:
#ifdef DEBUG
printf("The value of the debug version: %d\n", debug);
#else
printf("The value of the release version: %d\n", release);
#endif
If DEBUG has been defined by a #define directive, the value of the debug version is printed out by the printf()
function in the following statement:
printf("The value of the debug version: %d\n", debug);
Otherwise, if DEBUG has not been defined, the following statement is executed:
printf("The value of the release version: %d\n", release);
Now consider another example:
#if 1
printf("The line is always printed out.\n");
#endif
The printf() function is always executed because the expression 1 evaluated by the #if directive never returns 0.
In the following example:
#if MACRO_NAME1 || MACRO_NAME2
printf("MACRO_NAME1 or MACRO_NAME2 is defined.\n");
#else
printf("MACRO_NAME1 and MACRO_NAME2 are not defined.\n");
#endif
the logical operator || is used, along with MACRO_NAME1 and MACRO_NAME2 in the expression evaluated by
the #if directive. If one of the macro names, MACRO_NAME1 or MACRO_NAME2, has been defined, the
expression returns a nonzero value; otherwise, the expression returns 0.
The C preprocessor has another directive, #elif, which stands for "else if." You can use #if and #elif together to build
an if-else-if chain for multiple conditional compilation.
Saturday, October 17, 2009
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment