Main Content

AUTOSAR C++14 Rule M6-5-5

A loop-control-variable other than the loop-counter shall not be modified within condition or expression

Description

Rule Definition

A loop-control-variable other than the loop-counter shall not be modified within condition or expression.

Rationale

Loops are easier to understand and predict if loop-control-variables, other than loop counters, are not modified within the condition or increment/decrement expression. A volatile typed loop-control-variable is an exception and you can modify it outside of the statement without triggering this violation.

Loop-control-variables are any variables that occur in the loop init-statement, condition, or expression. Loop-control-variables include loop-counters and flags used for early loop termination. A loop-counter is a loop-control-variable that is:

  • Initialized prior to the for loop or in the init-statement of the for loop.

  • An operand to a relational operator in the condition of the for loop.

  • Modified in the expression of the for loop.

Polyspace Implementation

Polyspace® raises this defect whenever a loop-counter or flag used for early termination is modified within the condition or expression.

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 tf_test, tf_test2 = false;
int32_t x = 0;

bool a_test(bool a)
{
	if (x % 2 == 0)
	{
		a = true;
	}
	else
	{
		a = false;
	}
	return a;
}

void example()
{

	for (x = 0; (x < 10) && (tf_test = a_test(tf_test)); x++)        //noncompliant
	{
		//...
	}

	for (x = 0; (x < 10) && tf_test2; x++)         //compliant
	{
             //...
		tf_test2 = a_test(tf_test2);
	}
}

In the first for loop, because tf_test is a flag used for early loop termination that is modified within the condition, Polyspace flags it as noncompliant.

Check Information

Group: Statements
Category: Required, Automated

Version History

Introduced in R2019a