|
|
|
|
|
|
|
and pass in the values 5 and 7, the macro works as intended. But if you pass in a more complicated expression, you'll get unintended results, as shown in Listing 21.2. |
|
|
|
|
|
|
|
|
LISTING 21.2 USING PARENTHESES IN MACROS |
|
|
|
 |
|
|
|
|
1: // Listing 21.2 Macro Expansion
2: #include <iostream.h>
3:
4: #define CUBE(a) ( (a) * (a) * (a) )
5: #define THREE(a) a * a * a
6:
7: int main()
8: {
9: long x = 5;
10: long y = CUBE(x);
11: long z = THREE(x);
12:
13: cout << y: << y << endl;
14: cout << z: << z << endl;
15:
16: long a = 5, b = 7;
17: y = CUBE(a+b);
18: z = THREE(a+b);
19:
20: cout << y: << y << endl;
21: cout << z: << z << endl;
22: return 0;
23: } |
|
|
|
|
|
|
|
|
Output:y: 125
z: 125
y: 1728
z: 82 |
|
|
|
|
|
|
|
|
Analysis: On line 4 the macro CUBE is defined, with the argument x put into parentheses each time it is used. On line 5 the macro THREE is defined without the parentheses. |
|
|
|
|
|
|
|
|
In the first use of these macros, the value 5 is given as the parameter, and both macros work fine. CUBE(5) expands to ( (5) * (5) * (5) ), which evaluates to 125, and THREE(5) expands to 5 * 5 * 5, which also evaluates to 125. |
|
|
|
|
|
|
|
|
In the second use, on lines 1618, the parameter is 5 + 7. In this case, CUBE(5+7) evaluates to |
|
|
|
 |
|
|
|
|
( (5+7) * (5+7) * (5+7) ) |
|
|
|
 |
|
|
|
|
( (12) * (12) * (12) ) |
|
|
|
|
|