< previous page page_353 next page >

Page 353
and then write in your code
TWICE(4)
The entire string TWICE(4) will be removed, and the value 8 will be substituted! When the precompiler sees the 4, it will substitute ( (4) * 2 ), which will then evaluate 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 MAX and 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 forgiving of white space as is the compiler.
If you were to write
#define MAX (x,y) ( (x) > (y) ? (x) : (y) )
and then to try to use MAX like this,
int x = 5, y = 7, z;
z = MAX(x,y);
the intermediate code would be
int x = 5, y = 7, z;
z = (x,y) ( (x) > (y) ? (x) : (y) ) (x,y)
A simple text substitution would be done, rather than invoking the macro function. So the token MAX would have substituted for it (x,y) ( (x) > (y) ? (x) : (y) ), and then that would be followed by the (x,y) that followed MAX.
When the space between MAX and (x,y) is removed, however, the intermediate code becomes
int x = 5, y = 7, z;
z = 7;
Why All the Parentheses?
You may be wondering why there are so many parentheses in many of the macros presented so far. The preprocessor does not demand that parentheses be placed around the arguments in the substitution string. However, the parentheses help you to avoid unwanted side effects when you pass complicated values to a macro. For example, if you define MAX as
#define MAX(x,y) x > y ? x : y

 
< previous page page_353 next page >

If you like this book, buy it!