#else
is one of five preprocessor selection statements allowing selection of alternative sections of code for compilation. The other four selection statements are: #ifdef
, #ifndef
, #if
, and #elif
.
Behaviour of this preprocessor directive is the same for both C and C++ compilers.
Purpose
The #else
directive provides a final alternative for a preprocessor selection block. If all previous selection options fail, then the code found between the #else
and #endif
is compiled.
Format
#if or #ifdef or #ifndef
preprocessor or code statements
#elif controlling_expression (optional)
preprocessor or code statements
#else
preprocessor or code statements
#endif
All preprocessor directives begin with the #
symbol. It must be the first character on the line or the first character on the line following optional white space.
Some early compilers flagged an error if #
was not the first character on the line.
Spaces or tabs are permitted between the #
and else
, but not escape characters or other symbols or macros. The preprocessor removes white space and concatenates the #
and else
together.
If anything follows the #else
directive (other than white space) then the program is malformed.
The following are valid uses:
#else # else # /* comments are white space */ else
The following are invalid uses:
// #\ is not a valid preprocessor directive # \t else // #" is not a valid preprocessor directive # "" else // malformed because only white space may follow #else #else MY_MACRO
Use
The #else
must appear as the last alternative in a preprocessor selection block. If all the preceding selection options fail, then the code contained between the #else
and closing #endif
is compiled.
The statements following the #else
may be language statements or preprocessor statements. There is no limit on the nesting of preprocessor directives or statements.
#ifdef MY_MACRO . . . // these statements will only be compiled if MY_MACRO exists . . . #else . . . // these statements will only be compiled if MY_MACRO does not exist . . . #endif