MISRA C++:2008 Rule 6-5-1
A for loop shall contain a single loop-counter which shall not have floating type
Description
Rule Definition
A for loop shall contain a single loop-counter which shall not have floating type.
Rationale
A for
loop without a loop-counter can be replaced with a
while
loop. Use a while
loop instead in these
situations.
Floating-point types are rounded to fit into a finite representation. This causes rounding errors to be introduced with floating-point calculations which can cause unexpected results when performing comparisons.
Polyspace Implementation
This rule checker flags these situations:
The
for
loop index has a floating point type.More than one loop counter is incremented in the
for
loop increment statement.For instance:
for(i=0, j=0; i<10 && j < 10;i++, j++) {}
A loop counter is not incremented 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 raises a violation. 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 checker cannot find the loop counter modification and considers as if a loop counter is 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 |
Version History
Introduced in R2013b