Use of Parentheses in Macros

When a macro's replacement list is an expression, it should be enclosed in parentheses. Otherwise, the following may happen:

#define TWO_PI 2 * 3.14159

conversion_factor = 360 / TWO_PI;
/* conversion_factor = 360 / 2 * 3.14159; */
/* you really wanted: 360 / ( 2 * 3.14159 ) */
In a parameterized macro, each parameter should be enclosed in parentheses. If not, this may happen:

#define scale(x) (x * 10)

j = scale( i + 1 ); /* j = ( i + 1 * 10 ); */
/* your really wanted: ( ( i + 1 ) * 10 ) */
So be sure to use parentheses in you macro definitions:

#define max(x,y) ( x > y ) ? x : y   /* bad */
#define max(x,y) (((x)>(y))?(x):(y)) /* good */
Now consider the following use of a macro:

#define max(x,y) (((x)>(y))?(x):(y)) /* good */

x = max(a++,b++);
Assuming that a is 2 and b is 4 before max() is executed, we would expect, after executing the macro, to have a = 3 and b = 5, with x = 4.
Notice that the substitution of the macro yields:

x = ((a++)>(b++))?(a++):(b++));
So after the macro is executed a = 3 as expected, but b = 6, and x = 5. Clearly not what we intended! This occurs because b gets incremented twice in the code instead of just once. Since the other part of the conditional operator did not get executed, a was incremented only once. Unfortunately, all the parentheses in the world cannot correct this problem. So you must still be careful how you use macros in your program.
Hosted by www.Geocities.ws

1