Saturday, October 17, 2009

Nesting the #if directive

TYPE
Listing 23.4. Nesting the #if directive.
1: /* 23L04.c: Nesting #if */
2: #include
3:
4: /* macro definitions */
5: #define ZERO 0
6: #define ONE 1
7: #define TWO (ONE + ONE)
8: #define THREE (ONE + TWO)
9: #define TEST_1 ONE
10: #define TEST_2 TWO
11: #define TEST_3 THREE
12: #define MAX_NUM THREE
13: #define NO_ERROR ZERO
14: /* function declaration */
15: void StrPrint(char **ptr_s, int max);
16: /* the main() function */
17: main(void)
18: {
19: char *str[MAX_NUM] = {"The choice of a point of view",
20: "is the initial act of culture.",
21: "--- by O. Gasset"};
22:
23: #if TEST_1 == 1
24: #if TEST_2 == 2
25: #if TEST_3 == 3
26: StrPrint(str, MAX_NUM);
27: #else
28: StrPrint(str, MAX_NUM - ONE);
29: #endif
30: #else
31: StrPrint(str, MAX_NUM - TWO);
32: #endif
33: #else
34: printf("No TEST macro has been set.\n");
35: #endif
36:
37: return NO_ERROR;
38: }
39: /* function definition */
40: void StrPrint(char **ptr_s, int max)
41: {
42: int i;
43:
44: for (i=0; i
45: printf("Content: %s\n",
46: ptr_s[i]);
47: }
OUTPUT
The following output is shown on the screen after the executable 23L04.exe is created and run on my
machine:
C:\app>23L04
Content: The choice of a point of view
Content: is the initial act of culture.
Content: --- by O. Gasset
C:\app>
ANALYSIS
The purpose of the program in Listing 23.4 is to print the content of character strings controlled by the
nested #if directives.
At the beginning of the program, nine macro names are defined in lines 5_13. The prototype of a function, StrPrint(),
is given in line 15. Lines 19_21 define and initialize an array of char pointers called str.
The #if directives in lines 23_25 evaluate macro names, TEST_1, TEST_2, and TEST_3,
respectively. If the three macro names all return nonzero values, then in line 26, StrPrint() is invoked to print the
content of all character strings pointed to by the pointers in the str array.
If, however, only TEST_1 and TEST_2 are nonzero, the statement in line 28 prints out the content of the
MAX_NUM-ONE strings. Likewise, if only TEST_1 returns a nonzero value, the StrPrint() function is called in line
31 to print out the content of the MAX_NUM-TWO strings.
The last case is that TEST_1, TEST_2, and TEST_3 all return zero. Then the printf() function in line 34 is executed
to display the message No TEST macro has been set. onscreen.
As you can tell from the program in Listing 23.4, TEST_1, TEST_2, and TEST_3 are all defined with nonzero
constants; the content of all character strings referenced by the pointers of the str array are printed out as the output
from the program.
You're advised to change the value of the macros TEST_1, TEST_2, and TEST_3 to test the other executions in the
program.

No comments:

Post a Comment