Developer Documentation
PATH  Mac OS X Documentation > The GNU C Preprocessor

The GNU C Preprocessor

Previous | Contents | Next

Syntax of Conditionals

A conditional in the C preprocessor begins with a conditional command: #if , #ifdef , or #ifndef . These and a few related commands are described in the following sections.

The #if Command

The #if command in its simplest form consists of

#if expression
conditional-text
#endif /* expression */

The comment following the #endif isn't required, but it makes the code easier to read. Such comments should always be used, except in short conditionals that aren't nested. (Although you can put anything at all after the #endif and it will be ignored by the C preprocessor, only comments are acceptable in ANSI Standard C.)

expression is a C expression of type int , subject to stringent restrictions. It may contain:

sizeof operators and enum -type values aren't allowed. enum -type values, like all other identifiers that aren't taken as macro invocations and expanded, are treated as 0.

The controlled text inside a conditional can include preprocessor commands. Then the commands inside the conditional are obeyed only if that branch of the conditional succeeds. The text can also contain other conditional groups. However, the #if and #endif commands must balance.

The #else Command

The #else command can be added to a conditional to provide alternative text to be used if the condition is false:

#if expression
text-if-true
#else /* not expression */
text-if-false
#endif /* not expression */

If expression is nonzero, text-if-true is included; then #else acts like a failing conditional and text-if-false is ignored. If expression is 0, the #if conditional fails and text-if-false is included.

The #elif Command

A common use of nested conditionals is to check for more than two possible alternatives:

#if X == 1
. . .
#else /* X != 1 */
#if X == 2
. . .
#else /* X != 2 */
. . .
#endif /* X != 2 */
#endif /* X != 1 */

The conditional command #elif (which stands for "else if") can be used to abbreviate this as follows:

#if X == 1
. . .
#elif X == 2
. . .
#else /* X != 2 and X != 1*/
. . .
#endif /* X != 2 and X != 1*/

Like #else , #elif goes in the middle of a #if - #endif pair and subdivides it; it doesn't require a matching #endif of its own. Like #if , the #elif command includes an expression to be tested.

The text following the #elif is processed only if the original #if -condition failed and the #elif condition succeeds. More than one #elif can go in the same #if - #endif group. Then the text after each #elif is processed only if the #elif condition succeeds after the original #if and any previous #elif commands within it have failed. #else is allowed after any number of #elif commands, but #elif may not follow a #else .


The GNU C Preprocessor

Previous | Contents | Next