Main Content

MISRA C++:2008 Rule 5-0-2

Limited dependence should be placed on C++ operator precedence rules in expressions

Description

Rule Definition

Limited dependence should be placed on C++ operator precedence rules in expressions.

Rationale

Use parentheses to clearly indicate the order of evaluation.

Depending on operator precedence can cause the following issues:

  • If you or another code reviewer reviews the code, the intended order of evaluation is not immediately clear.

  • It is possible that the result of the evaluation does not meet your expectations. For instance:

    • In the operation *p++, it is possible that you expect the dereferenced value to be incremented. However, the pointer p is incremented before the dereference.

    • In the operation (x == y | z), it is possible that you expect x to be compared with y | z. However, the == operation happens before the | operation.

Troubleshooting

If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include <cstdio>

void showbits(unsigned int x) {
    for(int i = (sizeof(int) * 8) - 1; i >= 0; i--) {
       (x & 1u << i) ? putchar('1') : putchar('0'); // Noncompliant 
    }
    printf("\n");
}

In this example, the checker flags the operation x & 1u << i because the statement relies on operator precedence rules for the << operation to happen before the & operation. If this is the intended order, the operation can be rewritten as x & (1u << i).

Check Information

Group: Expressions
Category: Advisory

Version History

Introduced in R2013b