...
| Code Block | ||
|---|---|---|
| ||
#define sum a+b /* ... */ int result = sum*4; |
The value of result is a+(b*4) instead of the expected (a+b)*4.
Compliant Solution
Parenthesizing the macro yields the expected answer.
| Code Block | ||
|---|---|---|
| ||
#define sum (a+b) /* ... */ int result = sum*4; |
Note that there must be a space after sum, otherwise it becomes a function-like macro.
Exceptions
A macro that expands to a single identifier or function call will not change the precedence of any operators in the surrounding expression, so it need not be parenthesized.
| Code Block |
|---|
#define MY_PID getpid()
|
Risk Assessment
Failing to parenthesize around a function-like macro can result in unexpected arithmetic results.
...