主要内容

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

Assignment operators shall not be used in sub-expressions

描述

规则定义

Assignment operators shall not be used in sub-expressions. 1

理由

当在子表达式中使用时,赋值运算符会产生难以预测的副作用。这些副作用可能会产生与开发人员预期相反的结果。此规则有助于避免将赋值运算符 (=) 与等于运算符 (==) 混淆。不要在子表达式中使用赋值运算符。

Polyspace 实现

每当子表达式中包含赋值运算符时,Polyspace® 就会报告此缺陷。

故障排除

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

示例

全部展开

#include <cstdint>

bool example(int x, int y)
{
	if (x == 10) 		//Compliant
	{
		return true;
	}
	
       if ((x = y) == 0)            //Noncompliant
	{
		return false;
	}
	
	return false;
}

由于赋值运算符 = 被用在子表达式 (x = y) 中,因此 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.