The preprocessor supports conditional compilation of parts of a source file. This behavior is controlled by #if
, #else
, #elif
, #ifdef
, #ifndef
and #endif
directives.
#if expression | ||
#ifdef identifier | ||
#ifndef identifier | ||
#elif expression | ||
#else | ||
#endif |
The conditional preprocessing block starts with #if
, #ifdef
or #ifndef
directive, then optionally includes any number of #elif
directives, then optionally includes at most one #else
directive and is terminated with the #endif
directive. Any inner conditional preprocessing blocks are processed separately.
Each of #if
, #elif
, #else
, #ifdef
and #ifndef
directives control a code block until the first #elif
, #else
, #endif
directive not belonging to any inner conditional preprocessing blocks.
#if
, #ifdef
and #ifndef
directives test the specified condition (see below), and if it evaluates to true, compiles the controlled code block. In that case subsequent #else
and #elif
directives are ignored. Otherwise, if the specified condition evaluates false, the controlled code block is skipped and the subsequent #else
or #elif
directive (if any) is processed. In the former case, the code block controlled by the #else
directive is unconditionally compiled. In the latter case, the #elif
directive acts as if it were a #if
directive: checks for condition, compiles or skips the controlled code block based on the result, and in the latter case processes subsequent #elif
and #else
directives. The conditional preprocessing block is terminated by the #endif
directive.
#if, #elif
The expression is a constant expression, using only constants and identifiers, defined using #define
directive. Any identifier, which is not literal, non defined using #define
directive, evaluates to 0.
The expression may contain unary operators in form defined
identifier or defined (
identifier)
which return 1
if the identifier was defined using #define
directive and 0 otherwise. If the expression evaluates to nonzero value, the controlled code block is included and skipped otherwise. If any used identifier is not a constant, it is replaced with 0
.
Note: | (until C11) |
#ifdef, #ifndef
Checks if the identifier was defined using #define
directive.
#ifdef
identifier is essentially equivalent to #if defined
identifier.
#ifndef
identifier is essentially equivalent to #if !defined
identifier.
#define ABCD 2 #include <stdio.h> int main(void) { #ifdef ABCD printf("1: yes\n"); #else printf("1: no\n"); #endif #ifndef ABCD printf("2: no1\n"); #elif ABCD == 2 printf("2: yes\n"); #else printf("2: no2\n"); #endif #if !defined(DCBA) && (ABCD < 2*4-3) printf("3: yes\n"); #endif }
Output:
1: yes 2: yes 3: yes
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
http://en.cppreference.com/w/c/preprocessor/conditional