Main Content

AUTOSAR C++14 Rule A5-2-6

The operands of a logical && or || shall be parenthesized if the operands contain binary operators

Description

Rule Definition

The operands of a logical && or || shall be parenthesized if the operands contain binary operators.

Rationale

In a logical expression containing binary operators, relying on C++ operator precedence rules results in code that is confusing and difficult to understand. This code might lead to unexpected behavior and bugs that are difficult to resolve. Parenthesizing operands that include binary operators enhances the readability of code, makes code easier to review, and ensures that the operator precedence behavior is as expected.

Polyspace Implementation

During preprocessing, violations of this rule are detected on the expressions in #if directives.

The checker allows exceptions on associativity (a && b && c), (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

#include <cstdint>

void Fn(std::int32_t value) noexcept
{
  if (value > 1 && value < 2) { //Noncompliant
    // do some work
  } else if ((value > 0) && (value < 3)) { //Compliant
    // do some work
  } else if ((value == 0) || value == 3) { //Noncompliant
    // do some work
  } else if ((value < 0) || (value == 4)) { //Compliant
    // do some work
  } else {
    // do some work
  }
 
  return;
}

There are multiple uses of the logicals && and ||. In the first and third logical expressions, there are operands containing binary operators that are not parenthesized. Polyspace flags them as noncompliant with this rule. In the second and fourth logical expressions, all operands containing binary operators are parenthesized. Polyspace does not flag them as noncompliant with this rule.

Check Information

Group: Expressions
Category: Required, Automated

Version History

Introduced in R2019a

expand all