主要内容

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

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

The right hand operand of a logical && or || operator shall not contain side effects

描述

规则定义

The right hand operand of a logical && or || operator shall not contain side effects. 1

理由

当表达式被评估时,带有副作用的表达式会修改表达式中的至少一个变量。例如,n++ 是一个具有副作用的表达式。

a 的右操作数:

  • 逻辑运算符 && 仅在左操作数评估为 true 时进行求值。

  • 逻辑运算符 || 仅在左操作数评估为 false 时进行求值。

在其他情况下,右侧操作数不会被求值,因此表达式的副作用不会发生。如果您的程序依赖于副作用,那么在这些情况下可能会出现意外结果。

Polyspace 实现

检查项对右操作数为具有副作用的表达式的逻辑运算符 &&|| 进行标记。Polyspace® 假设:

  • 修饰至少一个变量的表达式具有副作用。

  • 声明但未定义的显式构造函数或转换函数没有副作用。定义的转换函数具有副作用。

  • 易失性访问和函数调用没有副作用。

故障排除

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

示例

全部展开

class real32_T {
public:
	real32_T() = default;

	/* Casting operations */
	explicit real32_T(float a) {
		// ...
	}
	/* Relational operators */
	bool operator==(real32_T a) const;
	bool operator>(real32_T a) const;
};

void bar() {
	real32_T d;


	
	if ((d == static_cast<real32_T>(0.0F))
	|| (static_cast<real32_T>(0.0F) > d)) {//Noncompliant
		/**/
	}
}



void foo(int i, int j){
	if(i==0 && ++j==i){ //Noncompliant
		--i;
	}
}

在函数 foo 中,运算符 && 的右操作数包含一个递增运算,该运算具有副作用。Polyspace 对该运算符进行标记。在函数 bar 中,运算符 || 的右操作数包含一个在类中实现的转换函数。Polyspace 认为此类构造函数具有副作用。由于正确的运算符具有副作用,因此该运算符被标记。

检查信息

组:表达式
类别:必需

版本历史记录

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