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.1
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
forloop index has a floating point type.More than one loop counter is incremented in the
forloop increment statement.For instance:
for(i=0, j=0; i<10 && j < 10;i++, j++) {}A loop counter is not incremented in the
forloop 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
1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.
The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:
MISRA C:2004
MISRA C:2012
MISRA C:2023
MISRA C++:2008
MISRA C++:2023
MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.