主要内容

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.1

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


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.