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
Check Information
Group: Statements |
Category: Required, Automated |