Skip to end of metadata
Go to start of metadata

Macros are often used to execute a sequence of multiple statements as a group.

Inline functions are, in general, more suitable for this task (see PRE00-C. Prefer inline or static functions to function-like macros). Occasionally, however, 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 EXP19-C. Use braces for the body of an if, for, or while statement).

Noncompliant Code Example

This noncompliant code example contains multiple, unbound statements:

/*
 * Swaps two values and requires
 * tmp variable to be defined.
 */
#define SWAP(x, y) \
  tmp = x; \
  x = y; \
  y = tmp

This macro expands correctly in a normal sequence of statements but not as the then clause in an if statement:

int x, y, z, tmp;
if (z == 0)
  SWAP(x, y);

It expands to the following, which is certainly not what the programmer intended:

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:

/*
 * 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:

if (x > y)
  SWAP(x, y);          /* Branch 1 */
else  
  do_something();     /* Branch 2 */

Following macro expansion, however, this code is interpreted as an if statement with only one branch:

if (x > y) { /* Single-branch if-statement!!! */

  tmp = x;   /* The one and only branch consists */
  x = y;     /* of the block. */
  y = tmp;
}
;            /* Empty statement */
else         /* ERROR!!! "parse error before else" */
  do_something();

The problem is the semicolon (;) following the block.

Compliant Solution

Wrapping the macro inside a do-while loop mitigates the problem:

/*
 * 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

Remediation Cost

Priority

Level

PRE10-C

Medium

Probable

Low

P12

L1

Automated Detection

ToolVersionCheckerDescription
Klocwork2017MISRA.DEFINE.BADEXP 
LDRA tool suite9.7.179 SEnhanced enforcement
PRQA QA-C9.3

3412, 3458

Fully implemented

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

ISO/IEC TR 24772:2013Pre-processor Directives [NMP]

Bibliography

 


12 Comments

    1. One problem with this rule is the MSVC2008 issues a warning about a constant conditional expression (the 'while(0)' makes it think you did something wrong.)

      I suppose this isn't a problem for Linux kernel developers, but how should Windows devs handle it?

      1. To be fair, MSVC only emits a diagnostic at /W4 or /Wall, which is rarely used in practice due to the verbosity vs quality of the diagnostics.  That being said, Microsoft turns this warning off in their header files when using this construct by doing #pragma warning(disable: 4127).

        1. Well, one of our rules is MSC00-C. Compile cleanly at high warning levels. We could always list this is an exception to the rule. Or instruct devs to suppress the warning using your #pragma.

          1. Would it make sense for a more comprehensive look at the list of warnings in /W4 and /Wall to list ones we feel are exceptions to the rule (or exceptional cases to the rule)?  Another one that immediately springs to mind is the conversion to bool performance warning with something like:

             

            bool func() { return 12; }
            1. Probably not.   1)  MSC00-C is a recommendation, not a rule.   2) it states "high warning levels", not necessarily the "highest warning levels".  3) It might make to add your observations concerning the usefulness of /W4 or /Wall on MSVC to MSC00-C.

  1. Much simpler solution.  Require the usage of brackets around the if -else clauses.  Then, this poblem goes away (plus, the if-else clauses are easier to read anyways.)

    1. This is a good solution if you can enforce bracketed-clauses on everyone who uses your macros. For instance. if you are developing in-house software, or closed-source software, then your company can enforce bracketed clauses for the software's lifetime.

      But if you cannot guarantee bracketed clauses from future devs, (which might happen if your company has no such policy, or you develop open-source software), this rule will still protect your multi-statement macros.

  2. Many developers understand why the first noncompliant example is wrong, but still think that e.g. #define SWAP(x,y) {tmp=x; x=y; y=tmp;} is fine, even though it fails as described at the kernelnewbies.org link above. It'd be useful to show a second noncompliant example that demonstrates why do...while is necessary, and not just { }.

  3. The SWAP() macro example seems a bit contrived.  Such a macro would either declare a temporary (and use an extension like __typeof__  to determine its type from the arguments) or be implemented as an (inline) function.  Similarly, rather than enclosing the macro body in a do { } while (0) statement, a macro that didn't introduce a temporary would preferably be written as an expression: (void)((tmp = (x)), ((x) = (y)), ((y) = tmp)).  In fact, I'm having trouble thinking of a macro that couldn't be implemented as a series of comma expressions if it didn't need to introduce a temporary.  In addition, the compliant solution violates PRE02-C by failing to parenthesize its macro arguments, and PRE12-C by evaluating each of the macro arguments twice.
    Is there an example of a multistatement macro that has a fully compliant solution that cannot be replaced by either an inline function or a comma expression? (I.e., a solution that doesn't violate any other CERT rules?)
    1. I added some text regarding PRE02-C and PRE12-C compliance. Since they are both recommendations, compliance is a good idea but not strictly mandatory.  I don't think the SWAP macro can be made compliant with PRE12-C.

      Many C++ features, and C11 features, such as inline functions, seemed to be designed to replace and obsolete macros. Including SWAP().  Certainly, SWAP() would be better implemented as a type-generic inline function for C11 (and C++11). EDIT: This would lose the works-on-any-type part of SWAP, but you could wrap an int-SWAP, float-SWAP, etc. into one macro or inline-function. You could have true type genericity if you are willing to use memcpy() rather than assignment.