You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 8 Next »

When defining macros, put parentheses around all variable names. This ensures that the macro is evaluated in a predictable manner. See also PRE02.

Non-Compliant Code Example

#define PRODUCT(A,B) A * B
int a = PRODUCT(3+4, 5)

PRODUCT(3+4, 5) is converted to 3+4 * 5 by the preprocessor, which the compiler intreprets as 3+(4*5) = 23. Presumably, this does not match the intended behavior of the macro, which is (3+4) * 5 = 35.

Compliant Solution

By adding parentheses around each argument, this macro (correctly) evaluates to 35.

#define PRODUCT(A,B) ((A) * (B))
int a = PRODUCT(3+4, 5)

References

comp.lang.c FAQ list - Question 10.1

  • No labels