Saturday, October 17, 2009

Using the #ifdef, #ifndef, and #endif Directives

TYPE
Listing 23.2. Using the #ifdef, #ifndef, and #endif directives.
1: /* 23L02.c: Using #ifdef, #ifndef, and #endif */
2: #include
3:
4: #define UPPER_CASE 0
5: #define NO_ERROR 0
6:
7: main(void)
8: {
9: #ifdef UPPER_CASE
10: printf("THIS LINE IS PRINTED OUT,\n");
11: printf("BECAUSE UPPER_CASE IS DEFINED.\n");
12: #endif
13: #ifndef LOWER_CASE
14: printf("\nThis line is printed out,\n");
15: printf("because LOWER_CASE is not defined.\n");
16: #endif
17:
18: return NO_ERROR;
19: }
OUTPUT
The following output is shown on the screen after the executable 23L02.exe is created and run:
C:\app>23L02
THIS LINE IS PRINTED OUT,
BECAUSE UPPER_CASE IS DEFINED.
This line is printed out,
because LOWER_CASE is not defined.
C:\app>
ANALYSIS
The purpose of the program in Listing 23.2 is to use #ifdef and #ifndef directives to control whether a
piece of message needs to be printed out.
Two macro names, UPPER_CASE and NO_ERROR, are defined in lines 4 and 5.
The #ifdef directive in line 9 checks whether the UPPER_CASE macro name has been defined. Because the macro
name has been defined in line 4, the two statements in lines 10 and 11 are executed before the #endif directive in line
12 marks the end of the #ifdef block.
In line 13, the #ifndef directive tells the preprocessor to include the two statements in lines 14 and 15 in the program
if the LOWER_CASE macro name has not been defined. As you can see, LOWER_CASE is not defined in the
program at all. Therefore, the two statement in lines 14 and 15 are counted as part of the program.
The output from running the program in Listing 23.2 shows that the printf() functions in lines 10, 11, 14, and 15 are
executed accordingly, under the control of the #ifdef and #ifndef directives.

No comments:

Post a Comment