...
When multiple statements are used in a macro, they should be bound together in a do-while loop syntactically, so the macro can appear safely inside if clauses or other places that expect a single statement or a statement block. Note that this is only effective if none of the multiple statements are break or continue, as they would be captured by the do-while loop. (Alternatively, when an if, for, or while statement uses braces even for a single body statement, then multiple statements in a macro will expand correctly even without a do-while loop (see EXP19-C. Use braces for the body of an if, for, or while statement).
...
| Code Block |
|---|
|
int x, y, z, tmp;
if (z == 0)
tmp = x;
x = y;
y = tmp;
|
Furthermore, this macro violates PRE02-C. Macro replacement lists should be parenthesized.
Noncompliant Code Example
This noncompliant code example parenthesizes its macro arguments, but inadequately bounds multiple statements:
| Code Block |
|---|
|
/*
* Swaps two values and requires
* tmp variable to be defined.
*/
#define SWAP(x, y) { tmp = (x); (x) = (y); (y) = tmp; }
|
This macro fails to expand correctly in some case, such as the following example, which is meant to be an if statement with two branches:
...
| Code Block |
|---|
|
/*
* Swaps two values and requires
* tmp variable to be defined.
*/
#define SWAP(x, y) \
do { \
tmp = (x); \
(x) = (y); \
(y) = tmp; } \
while (0)
|
The do-while loop will always be executed exactly once.
This macro still violates the recommendation PRE12-C. Do not define unsafe macros, because both macro arguments are evaluated twice. It is expected that the arguments are simple lvalues.
Risk Assessment
Improperly wrapped statement macros can result in unexpected and difficult to diagnose behavior.
Recommendation | Severity | Likelihood | Detectable |
|---|
Remediation CostRepairable | Priority | Level |
|---|
PRE10-C | Medium | Probable |
LowAutomated Detection
PRQA QACPRQA QACvPRQA QACv3412, 3458
| Fully implemented Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
Bibliography
...
...
Image Modified
Image Modified
Image Modified