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

Compare with Current View Page History

Version 1 Next »

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

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 will then intrepret as 3+(4*5) = 23. This does not match what the macro name implies the behavior to be, which is (3+4) * 5 = 35.

Compliant Code Example

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

Due to the parentheses, this macro is evaluated to 35, matching what the macro name implies it should.

  • No labels