Sams Teach Yourself C++ in 21 Days

(singke) #1
What’s Next 757

21


The entire string TWICE(4)is removed, and the value ( (4) 2 )is substituted. When
the precompiler sees the 4 , it substitutes ( (4)
2 ), which then evaluates to 4 * 2,
or 8.


A macro can have more than one parameter, and each parameter can be used repeatedly
in the replacement text. Two common macros are MAXand MIN:


#define MAX(x,y) ( (x) > (y)? (x) : (y) )
#define MIN(x,y) ( (x) < (y)? (x) : (y) )


Note that in a macro function definition, the opening parenthesis for the parameter list
must immediately follow the macro name, with no spaces. The preprocessor is not as for-
giving of whitespace as is the compiler. If there is a space, a standard substitution is used
like you saw earlier in today’s lesson.


For example, if you write:


#define MAX (x,y) ( (x) > (y)? (x) : (y) )


and then try to use MAXlike this:


int x = 5, y = 7, z;
z = MAX(x,y);


the intermediate code is


int x = 5, y = 7, z;
z = (x,y) ( (x) > (y)? (x) : (y) )(x,y)


A simple text substitution is done, rather than invoking the macro function. Thus, the
token MAXhas substituted for it (x,y) ( (x) > (y)? (x) : (y) ), and then that is
followed by the (x,y), which follows MAX.


By removing the space between MAXand (x,y), however, the intermediate code becomes:


int x = 5, y = 7, z;
a = ( (5) > (7)? (5) : (7) );


This, of course, then evaluates to 7.


Why All the Parentheses? ..............................................................................


You might be wondering why so many parentheses are in many of the macros presented
so far. The preprocessor does not demand that parentheses be placed around the argu-
ments in the substitution string, but the parentheses help you to avoid unwanted side
effects when you pass complicated values to a macro. For example, if you define MAXas


#define MAX(x,y) x > y? x : y

Free download pdf