Macro with multiple statements
Macro consists of multiple semicolon-terminated statements, enclosed in braces or not
Since R2020a
Description
This defect occurs when a macro contains multiple semicolon-terminated statements, irrespective of whether the statements are enclosed in braces.
Risk
The macro expansion, in certain contexts such as an if
condition or a
loop, can lead to unintended program logic.
For instance, consider the macro:
#define RESET(x,y) \ x=0; \ y=0;
if
statement such
as:if(checkSomeCondition) RESET(x,y);
if(checkSomething) x=0; y=0;
if
block.Fix
In a macro definition, wrap multiple statements in a do...while(0)
loop.
For instance, in the preceding example, use the definition:
#define RESET(x,y) \ do { \ x=0; \ y=0; \ } while(0)
while(0)
ensures that
the statements are executed only once.Alternatively, use inline functions in preference to function-like macros that involve multiple statements.
Note that the loop is required for the correct solution and wrapping the statements in braces alone does not fix the issue. The macro expansion can still lead to unintended code.
Examples
Result Information
Group: Good practice |
Language: C | C++ |
Default: Off |
Command-Line Syntax:
MULTI_STMT_MACRO |
Impact: Low |
Version History
Introduced in R2020a
See Also
Find defects
(-checkers)
| Macro terminated with a
semicolon
| Incorrectly indented
statement
| Semicolon on same line as if, for or
while statement
Topics
- Interpret Bug Finder Results in Polyspace Desktop User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Results in Polyspace User Interface Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)