主要内容

本页采用了机器翻译。点击此处可查看最新英文版本。

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

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

描述

规则定义

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

理由

该规则实际上要求逻辑运算符 &&|| 的操作数必须正确地用括号括起来。例如,规则要求使用 (a + b) || ca + (b || c),而不是 a + b || c。在这两个合规的情况下,|| 的左操作数,即 (a + b)b,都是主要表达式,因此也是后缀表达式。有关后置表达式的更多信息,请参阅 C++03 标准(第 5.2 节)。

将操作数用括号括起来可以提高代码的可读性,并确保运算按照开发者意图的顺序执行。

Polyspace 实现

如果逻辑运算符 &&|| 不是后置表达式,检查项将引发违规。

后置表达式可以是基本表达式,如简单标识符或用括号括起的标识符组合,也可以是以下之一:

  • 函数调用,如 func()

  • 数组元素访问,例如 arr[]

  • 结构成员访问,例如 aStructVar.aMember

有关后置表达式的完整列表,请参阅 C++03 标准(第 5.2 节)。

检查项允许关联链中的例外,例如 (a && b && c)(a || b || c)

故障排除

如果您预期会出现违规,而 Polyspace® 未报告该违规,请参阅诊断为何编码规范违规未按预期显示

示例

全部展开

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;
}

在此示例中,表达式 a && b || c 违反了规则,因为 && 的右操作数和 || 的左操作数不是后缀表达式。

检查信息

组:表达式
类别:必需

版本历史记录

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