When defining macros, put parentheses around all variable names. This ensures that the macro is evaluated in a predictable manner.
...
Code Block |
---|
#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 intreprets as 3+(4*5) = 23
. This Presumably, this does not match what the intended behavior of the macro name implies the behavior to be, which is (3+4) * 5 = 35
.
Compliant Code Example
Code Block |
---|
#define PRODUCT(A,B) (A) * (B) int a = PRODUCT(3+4, 5) |
Due to the parenthesesBy adding parentheses around each argument, this macro is evaluated (correctly) evaluates to 35, matching what the macro name implies it should.