Main Content

MISRA C++:2023 Rule 8.18.2

The result of an assignment operator should not be used

Since R2024b

Description

Rule Definition

The result of an assignment operator should not be used.

Rationale

Using an assignment operation inside a larger expression can reduce the readability of the code.

In addition, when used in a subexpression, assignment operators have side effects that are difficult to track and might produce results contrary to developer expectations.

Polyspace Implementation

The rule checker reports a violation when an assignment operation is a subexpression inside a larger expression. The checker makes an exception for the case when the subexpression is unevaluated, for instance, inside a sizeof operator.

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>

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

Because the assignment operator = is used in the subexpression (x = y), Polyspace flags it as noncompliant.

Check Information

Group: Expressions
Category: Advisory

Version History

Introduced in R2024b