Wednesday, November 2, 2011

#if and #elif Directives types of the The C Preprocessor in C programming language

The #if directive can be used to test whether an expression evaluates to a nonzero value or not. If the result of the expression is nonzero, then subsequent lines upto a #else, #elif or #endif are compiled, otherwise they are skipped.
A simple example of #if directive is shown below:
main( )
{
#if TEST <= 5
statement 1 ;
statement 2 ;
statement 3 ;
#else
statement 4 ;
statement 5 ;
statement 6 ;
#endif
}
If the expression, TEST <= 5 evaluates to true then statements 1, 2 and 3 are compiled otherwise statements 4, 5 and 6 are compiled. In place of the expression TEST <= 5 other expressions like ( LEVEL == HIGH || LEVEL == LOW ) or ADAPTER == CGA can also be used.
If we so desire we can have nested conditional compilation directives. An example that uses such directives is shown below.
#if ADAPTER == VGA
code for video graphics array
#else
#if ADAPTER == SVGA
code for super video graphics array
#else
code for extended graphics adapter
#endif
#endif
The above program segment can be made more compact by using another conditional compilation directive called #elif. The same program using this directive can be rewritten as shown below.
Observe that by using the #elif directives the number of #endifs used in the program get reduced.
#if ADAPTER == VGA
code for video graphics array
#elif ADAPTER == SVGA
code for super video graphics array
#else
code for extended graphics adapter
#endif

No comments:

Post a Comment