Main Content

MISRA C++:2023 Rule 9.3.1

The body of an iteration-statement or a selection-statement shall be a compound-statement

Since R2024b

Description

Rule Definition

The body of an iteration-statement or a selection-statement shall be a compound-statement.

Rationale

When used in a subexpression, assignment operators have side effects that are difficult to predict. These side effects might produce results contrary to developer expectations. This rule helps in avoiding confusion between the assignment operator (=) and the equal to operator (==). Do not use the result of an assignment operator.

Polyspace Implementation

Polyspace® raises this defect whenever a subexpression contains an assignment 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: Statements
Category: Required

Version History

Introduced in R2024b