The #else preprocessor directive is used with the #if
, #ifdef
, #ifndef
directives. The preprocessor includes the code in the #else
directive if the condition in the #if
, #ifdef
or #ifndef
is not met.
The #else
directive must be closed with a #endif
directive.
#else
/*
your code here
*/
#endif
#include<stdio.h> int main() { #if 1 < 0 printf("The code in #if directive is run\n"); #else printf("The code in #else directive is run\n"); #endif return 0; }
The code above demonstrates how to use the #else
directive.
The conditional expression in the #if
directive evaluates to either zero or a non-zero value. If it evaluates to a non-zero value, the preprocessor selects the code in the #if
block. If the expression evaluates to 0, the code in the #else
directive is run.
The preprocessor passes the selected code block to the compiler for compilation. Together with the #if
, #ifdef
and #ifndef
directives, the #else
directive can be used for conditionally compiling certain portions of the source code.
Try changing the expression in the following code to see how conditional compilation works:
#if 1 < 0
RELATED TAGS
CONTRIBUTOR
View all Courses