Main Content

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

Each operand of a logical && or || shall be a postfix-expression

Description

Rule Definition

Each operand of a logical && or || shall be a postfix-expression.

Rationale

This rule effectively requires that operands of a logical && or || operation be appropriately parenthesized. For instance, instead of a + b || c, the rule requires (a + b) || c or a + (b || c). In both compliant cases, the left operand of ||, that is (a + b) or b, is a primary expression and therefore also a postfix expression. For more information on postfix expressions, see the C++03 Standard (Section 5.2).

Enclosing operands in parentheses improves readability of code and makes sure that the operations occur in the order that the developer intends.

Polyspace Implementation

The checker raises a violation if a logical && or || operand is not a postfix expression.

A postfix expression can be a primary expression such as a simple identifier or a combination of identifiers enclosed in parentheses, but also one of the following:

  • Function call such as func().

  • Array element access such as arr[].

  • Structure member access such as aStructVar.aMember.

For the complete list of postfix expressions, see the C++03 Standard (Section 5.2).

The checker allows exceptions on associative chains such as (a && b && c) or (a || b || c).

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

bool Operations(bool a, bool b, bool c, bool priority) {
    bool res;
    if(priority) {
        res = a && b || c;  //Noncompliant
    }
    else {
        res = a && (b || c); //Compliant
    }
    return res;
}

In this example, the expression a && b || c violates the rule because the right operand of && and the left operand of || are not postfix expressions.

Check Information

Group: Expressions
Category: Required

Version History

Introduced in R2013b