Sams Teach Yourself C++ in 21 Days

(singke) #1
and pass in the values 5 and 7 , the macro works as intended. But, if you pass in a more
complicated expression, you receive unintended results, as shown in Listing 21.2.

LISTING21.2 Using Parentheses in Macros
0: // Listing 21.2 Macro Expansion
1: #include <iostream>
2: using namespace std;
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: }

y: 125
z: 125
y: 1728
z: 82
On line 4, the macro CUBEis defined, with the argument xput into parentheses
each time it is used. On line 5, the macro THREEis defined, without using paren-
theses.
In the first use of these macros on lines 10 and 11, 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 16 to 18, the parameter is 5 + 7. In this case,CUBE(5+7)
evaluates to
( (5+7) * (5+7) * (5+7) )

OUTPUT


758 Day 21


ANALYSIS
Free download pdf