Wiki Markup |
---|
The macro expansion must always be parenthesized to protect any lower-precedence operators from the surrounding expression. See also \[[PRE01|PRE01-A. Use parentheses within macros around variable names]\]. |
Non-Compliant Code Example
This PRODUCT CUBE()
macro definition is non-compliant because it fails to parethesize the macro expansion.
Code Block |
---|
#define PRODUCT(A,B) (ACUBE(X, Y, Z) (X) * (Y) * (BZ) int n, mi = 3; int a = 181 / PRODUCT(n, m)CUBE(i); |
As a result, the invocation 1 / PRODUCT(n, m)
Code Block |
---|
int a = 81 / CUBE(i);
|
expands to
1 / n * m
Code Block |
---|
int a = 81 / i * i * i
|
which evaluates as
Code Block |
---|
int a = ((81 / i) * i) * i) // evaluates to 243
|
(which evaluates as (1 / n) * m), while the desired behavior is clearly
1 / (n * m)
Code Block |
---|
int a = 81 / ( i * i * i) // evaluates to 3
|
...
Compliant Solution
By adding parentheses around each argument, this definition of the PRODUCT CUBE()
macro expands correctly in this situation.
Code Block |
---|
#define PRODUCTCUBE(A,BX) ((X) * (AX) * (BX) ) int i n,= m3; int a = 181 / PRODUCT(n, m)CUBE(i); |
However, if a parameter appears several times in the expansion, the macro may not work properly if the actual argument is an expression with side effects. Given the PRODUCTCUBE() macro above, the invocation:
PRODUCT(i+, i+);
would expand to
i++ * i++
which is undefined. This is less obvious in the case of the CUBE() macro below:
Code Block |
---|
#define CUBE(X, Y, Z) ( (X) * (Y) * (Z)) int ia = 3; int a =81 / CUBE(i++); |
The CUBE() macro in this expression expands to:
int a = 81 / (i++ * i++ * i++);
Wiki Markup |
---|
Which is |
References
...
undefined (see \[[EXP30|EXP30-C. Do not depend on order of evaluation between sequence points]\] |
References
- Summit 05 Question 10.1