Main Content

AUTOSAR C++14 Rule A6-5-2

A for loop shall contain a single loop-counter which shall not have floating-point type

Description

Rule Definition

A for loop shall contain a single loop-counter which shall not have floating-point type.

Rationale

In situations where your code has a for loop without a loop counter, replace the for loop with a while loop.

In floating-point arithmetic operations, floating-point types are rounded to fit into a finite representation. This introduces rounding errors which can cause unexpected results when loop-counter comparisons occur.

Polyspace Implementation

This rule checker reports a rule violation in these situations:

  • The for loop index has a floating-point type.

  • You increment more than one loop counter in the for loop increment statement.

    For instance:

    for(i=0, j=0; i<10 && j < 10;i++, j++) {}

  • You do not increment a loop counter in the for loop increment statement.

    For instance:

    for(i=0; i<10;) {}

    Even if you increment the loop counter in the loop body, Polyspace® still reports a violation. The rule is based on MISRA™ C++ rule 6-5-1. According to the MISRA C++ specifications, a loop counter is one that is initialized in or prior to the loop expression, acts as an operand to a relational operator in the loop expression, and is modified in the loop expression. If the increment statement in the loop expression is missing, the rule checker cannot find the loop counter modification and considers the loop counter not present.

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

Because the code increments both loop counters, x and i, this example is noncompliant.

#include <iostream>

int main()
{
	int x = 0;
	for (int i = 0; i >= x; i = x++)   // Non-compliant
	{
		//...
	}
}

In this noncompliant example, because floating-point calculations contain rounding errors, the for loop executes only nine times. This is due to the value of x being larger than 1.0f on the tenth loop.

#include <iostream>

int main()
{
	for (float x = 0.1f; x <= 1.0f; x += 0.1f) {   //Noncompliant
		std::cout << x << std::endl;
	}
}

Check Information

Group: Statements
Category: Required, Automated

Version History

Introduced in R2019a

expand all