Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-868

Operands of "&&" and "||" should be primary (C) or postfix (C++) expressions

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Add parenthesis around complex operands.
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Legacy Key:
      LogicalExpressionOperands
    • Covered Languages:
      C, C++, Objective-C
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      10min
    • MISRA C 2004:
      12.5
    • MISRA C++ 2008:
      5-2-1

      Description

      The effect of this rule is to require that operands are appropriately parenthesized. Parentheses are important in this situation both for readability of code and for ensuring that the behavior is as the developer intended.
      Where an expression consists of either a sequence of only logical && or a sequence of logical ||, extra parentheses are not required.

      Noncompliant Code Example

      if (x == 0 && ishigh);                   // Noncompliant
      if (x || y || z);
      if (x || y && z);                        // Noncompliant
      if (x && !y);                            // Noncompliant
      if (is_odd(y) && x);
      if ((x > c1) && (y > c2) && (z > c3));
      if ((x > c1) && (y > c2) || (z > c3));   // Noncompliant
      

      Compliant Solution

      if ((x == 0) && ishigh);
      if (x || y || z);
      if (x || (y && z));
      if (x && (!y));
      if (is_odd(y) && x);
      if ((x > c1) && (y > c2) && (z > c3));
      if ((x > c1) && ((y > c2) || (z > c3)));
      

      See

      • MISRA C:2004, 12.5 - The operands of a logical && or || shall be primary-expressions.
      • MISRA C++:2008, 5-2-1 - Each operand of a logical && or || shall be a postfix-expression.

        Attachments

          Issue Links

          1.
          C-Family RSPEC-4385 Language-Specification Active Unassigned

            Activity

              People

              • Assignee:
                Unassigned
                Reporter:
                Anonymous
              • Votes:
                0 Vote for this issue
                Watchers:
                1 Start watching this issue

                Dates

                • Created:
                  Updated: