Listing 23.3. Using the #if, #elif, and #else directives.
1: /* 23L03.c: Using #if, #elif, and #else */
2: #include
3:
4: #define C_LANG `C'
5: #define B_LANG `B'
6: #define NO_ERROR 0
7:
8: main(void)
9: {
10: #if C_LANG == `C' && B_LANG == `B'
11: #undef C_LANG
12: #define C_LANG "I know the C language.\n"
13: #undef B_LANG
14: #define B_LANG "I know BASIC.\n"
15: printf("%s%s", C_LANG, B_LANG);
16: #elif C_LANG == `C'
17: #undef C_LANG
18: #define C_LANG "I only know C language.\n"
19: printf("%s", C_LANG);
20: #elif B_LANG == `B'
21: #undef B_LANG
22: #define B_LANG "I only know BASIC.\n"
23: printf("%s", B_LANG);
24: #else
25: printf("I don't know C or BASIC.\n");
26: #endif
27:
28: return NO_ERROR;
29: }
OUTPUT
After the executable 23L03.exe is created and run, the following output is displayed on the screen:
C:\app>23L03
I know C language.
I know BASIC.
C:\app>
ANALYSIS
The purpose of the program in Listing 23.3 is to use the #if, #elif, and #else directives to select portions
of code that are going to be compiled.
Inside the main() function, the #if directive in line 10 evaluates the conditional expression C_LANG == `C' &&
B_LANG == `B'. If the expression returns nonzero, then statements in lines 11_15 are selected to be compiled.
In line 11 the #undef directive is used to remove the C_LANG macro name. Line 12 then redefines C_LANG with
the string "I know the C language.\n". Likewise, line 13 removes the B_LANG macro name and line 14 redefines
B_LANG with another character string. The printf() function in line 15 prints the two newly assigned strings
associated with C_LANG and B_LANG.
The #elif directive in line 16 starts to evaluate the expression C_LANG == `C' if the expression in line 10 fails to
return a nonzero value. If the C_LANG == `C' expression returns nonzero, the statements in lines 17_19 are
compiled.
If, however, the expression in line 16 also fails to return a nonzero value, the B_LANG == `B' expression in line 20 is
evaluated by another #elif directive. The statements in lines 21_23 are skipped, and the statement in line 25 is
compiled finally if the B_LANG == `B' expression returns 0.
In line 26 the #endif directive marks the end of the #if block that starts on line 10.
From the program in Listing 23.3 you can tell that C_LANG and B_LANG have been properly defined in lines 4 and
5. Therefore, the statements in lines 11_15 are selected as part of the program and compiled by the C compiled. The
two character strings assigned to C_LANG and B_LANG during the redefinition are printed out after the program in
Listing 23.3 is executed.
You're advised to change the value of the macros C_LANG and B_LANG to test the other executions in the program.

No comments:
Post a Comment