Macros are often used to execute a sequence of multiple statements as a group.
While inline Inline functions are, in general, more suitable for this task. (see See guideline PRE00-C. Prefer inline or static functions to function-like macros.) Occasionally, however, occasionally they are not feasible (when macros are expected to operate on variables of different types, for example).
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. (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 guideline EXP19-C. Use braces for the body of an if, for, or while statement.)
Noncompliant Code Example
...
Code Block | ||
---|---|---|
| ||
int x, y, z, tmp; if (z == 0) tmp = x; x = y; y = tmp; |
which This is certainly not what the programmer intended.
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Other Languages
Related Guidelines
This rule appears in the C++ Secure Coding Standard as : PRE10-CPP. Wrap multi-statement macros in a do-while loop.
Bibliography
Wiki Markup |
---|
\[[ISO/IEC PDTR 24772|AA. Bibliography#ISO/IEC PDTR 24772]\] "NMP Pre-processor Directions" [Linux Kernel Newbies FAQ|http://kernelnewbies.org/FAQ] [FAQ/DoWhile0|http://kernelnewbies.org/FAQ/DoWhile0] |
...