When defining macros, put parentheses around Parenthesize all variable names . This ensures that the macro is evaluated in a predictable mannerin macro definitions. See also PRE02.
Non-Compliant Code Example
This CUBE()
macro definition is non-compliant because it fails to parethesize the variable names.
Code Block |
---|
#define PRODUCTCUBE(A,B) AI) (I * I * BI) int ac = 81 / PRODUCTCUBE0(32 +4, 51); |
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
As a result, the invocation
Code Block |
---|
int c = 81 / CUBE0(2 + 1);
|
expands to
Code Block |
---|
int a = 81 / (2 + 1 * 2 + 1 * 2 + 1); /* evalutaes to 11 */
|
while the desired behavior is
Code Block |
---|
int a = 81 / ( (2 + 1) * (2 + 1) * (2 + 1)); /* evaluates to 3 */
|
Compliant Solution
Parenthesizing all variable namesthe in the{{CUBE()}} macro allows it to expand correctly (when invoked in this manner)By adding parentheses around each argument, this macro (correctly) evaluates to 35.
Code Block |
---|
#define PRODUCTCUBE(A,BI) ( (I) * (AI) * (BI) ) int ac = PRODUCT(3+4, 5) |
References
81 / CUBE(2 + 1);
|
Priority: P3 Level: L3
Component | Value |
---|---|
Severity | 1 (low) |
Likelihood | 1 (unlikely) |
Remediation cost | 3 (low) |
References
- Summit 05 Question 10.1
- ISO/IEC 9899-1999 Section 6.10 Preprocessing directives
...