Trouble With Macros

Macros may seem like a great idea at first, but it is important to use them with caution. A macro is not a function. Consider the macro MAX defined like this:

#define MAX(a,b) (((a)>(b)) ? (a) : (b))

The problem with such a definition is that either a or b may be evaluated twice when the macro is included. This is no problem when a and b are just variable names, but consider this:

z = MAX(++x,y);  /* Increase x by 1 and set z to the maximum of the new x and y */

That gets expanded to this:

z = (((++x)>(y) ? (++x) : (y));

This does not do what the comment says (and might reasonably have been expected for a function call). This increments x by 1, compares the new value to y, and if the incremented value is greater than y it increments x again and sets z to that value. On the other hand, if y is greater than the starting x value plus one then x is only incremented by one and z is set to the value of y.

The moral of the story is to be very careful when using arguments to macros which might have side effects. Also, consider what happens if you put a function call in as one of the arguments to a macro like that. Yes, it could get called more than once (which might not be what you wanted).