Main Content

MISRA C:2012 Rule 20.7

Expressions resulting from the expansion of macro parameters shall be enclosed in parentheses

Description

Rule Definition

Expressions resulting from the expansion of macro parameters shall be enclosed in parentheses.

Rationale

If you do not use parentheses, then it is possible that operator precedence does not give the results that you want when macro substitution occurs.

If you are not using a macro parameter as an expression, then the parentheses are not necessary because no operators are involved in the macro.

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#define mac1(x, y) (x * y)
#define mac2(x, y) ((x) * (y))

void foo(void){
    int r;

    r = mac1(1 + 2, 3 + 4);       /* Non-compliant */
    r = mac1((1 + 2), (3 + 4));   /* Compliant */

    r = mac2(1 + 2, 3 + 4);       /* Compliant */
}

In this example, mac1 and mac2 are two defined macro expressions. The definition of mac1 does not enclose the arguments in parentheses. In line 7, the macro expands to r = (1 + 2 * 3 + 4); This expression can be (1 + (2 * 3) + 4) or (1 + 2) * (3 + 4). However, without parentheses, the program does not know the intended expression. Line 8 uses parentheses, so the line expands to (1 + 2) * (3 + 4). This macro expression is compliant.

The definition of mac2 does enclose the argument in parentheses. Line 10 (the same macro arguments in line 7) expands to (1 + 2) * (3 + 4). This macro and macro expression are compliant.

Check Information

Group: Preprocessing Directives
Category: Required
AGC Category: Required

Version History

expand all