The #if, #elif, #else, and #endif Conditional Directives

The #if, #elif, #else, and #endif directives are used together to allow lines of source code to be conditionally included or excluded from the compilation of a source file. The #if directive, which begins all conditional blocks, must be matched by a closing #endif directive.

Syntax

#if <expression1>

    code to be included

#elif <expression2>

    code to be included

#else

    code to be included

#endif

The expression following the #if and #elif directives must be a valid boolean expression, comprised of boolean operators and using identifiers declared with the #define or #undef compiler directives. If the expression following the #if directive evaluates to true, lines immediately following the directive are retained in the source file. If, however, the expression has the value false, the lines immediately following the directive are excluded from the source file until the #elif, #else, or #endif directive is encountered.

Only one #else directive can be included in a conditional block. Lines following the #else directive are retained in the source file only if the associated expression evaluated by the #if directive evaluates to false.

Zero or more #elif directives can be included within a conditional block of code. The #elif directive, an abbreviation of "else if," is used for subsequent evaluation of expressions, where the #if directive has already been evaluated and proven to be false.

Expressions used in conditional compilation have some of the same limitations and behaviors as those imposed by the Java language. For example, all the Java defined boolean and bitwise operators are accepted, and operator precedence is identical. Furthermore, the Java language also defines the use of parenthesis to force the order of evaluation.

The following example illustrates using each of these conditional directives:

#define DEBUG
#undef RETAIL

public class test {
     
    #if DEBUG
        if (cmdStatus.equals(invokeError))
        {
            // The following line displays a diagnostic message:
            System.out.println("Error: command timed out.");
            // appropriate actions
            // taken here
        }
    #elif RETAIL
        if (cmdStatus.equals(invokeError))
        {
            // appropriate actions
            // taken here
        }
    #else
        #error Must define DEBUG or RETAIL;
    #endif
}