Saturday, October 17, 2009

Example of Using the #define Directive to Perform Macro Substitution

TYPE
Listing 23.1. Using the #define directive.
1: /* 23L01.c: Using #define */
2: #include
3:
4: #define METHOD "ABS"
5: #define ABS(val) ((val) < 0 ? -(val) : (val))
6: #define MAX_LEN 8
7: #define NEGATIVE_NUM -10
8:
9: main(void)
10: {
11: char *str = METHOD;
12: int array[MAX_LEN];
13: int i;
14:
15: printf("The orignal values in array:\n");
16: for (i=0; i
17: array[i] = (i + 1) * NEGATIVE_NUM;
18: printf("array[%d]: %d\n", i, array[i]);
19: }
20:
21: printf("\nApplying the %s macro:\n", str);
22: for (i=0; i
23: printf("ABS(%d): %3d\n", array[i], ABS(array[i]));
24: }
25:
26: return 0;
27: }
OUTPUT
The following output appears on the screen after you run the executable 23L01.exe of the program in
Listing 23.1:
C:\app>23L01
The orignal values in array:
array[0]: -10
array[1]: -20
array[2]: -30
array[3]: -40
array[4]: -50
array[5]: -60
array[6]: -70
array[7]: -80
Applying the ABS macro:
ABS(-10): 10
ABS(-20): 20
ABS(-30): 30
ABS(-40): 40
ABS(-50): 50
ABS(-60): 60
ABS(-70): 70
ABS(-80): 80
C:\app>
ANALYSIS
The purpose of the program in Listing 23.1 is to define different macro names, including a function-like
macro, and use them in the program.
In lines 4_7, four macro names, METHOD, ABS, MAX_LEN, and NEGATIVE_NUM are defined with the #define
directive. Among them, ABS can accept one argument. The definition of ABS in line 5 checks the value of the
argument and returns the absolute value of the argument. Note that the conditional operator ?: is used to find the
absolute value for the incoming argument. (The ?: operator was introduced in Hour 8, "More Operators.")
Then, inside the main() function, the char pointer str is defined and assigned with METHOD in line 11. As you can
see, METHOD is associated with the string "ABS". In line 12, an int array called array is defined with the element
number specified by MAX_LEN.
In lines 16_19, each element of array is initialized with the value represented by the (i + 1) * NEGATIVE_NUM
expression that produces a series of negative integer numbers.
The for loop in lines 22_24 applies the function-like macro ABS to each element of array and obtains the absolute
value for each element. Also, all absolute values are printed on the screen. The output from the program in Listing
23.1 proves that each macro defined in the program works very well.

No comments:

Post a Comment