MISRA C:2012 Rule 14.1
A loop counter shall not have essentially floating type
Description
Rule Definition
A loop counter shall not have essentially floating type1 .
Rationale
When using a floating-point loop counter, accumulation of rounding errors can cause the actual number of iterations to be different than the number of iterations you expect. This rounding error can happen when a loop step that is not a power of the floating-point radix is rounded to a value that can be represented by a float.
Even if a loop with a floating-point loop counter appears to behave correctly on one implementation, it can give a different number of iterations on another implementation.
Polyspace Implementation
Polyspace® reports a violation of this rule if a loop counter variable has an essentially floating type.
To determine if a variable is a loop counter, the checker considers only the controlling expression of the loop. In particular:
If you use a floating point variable to break out of a loop but do not use this variable in the loop controlling expression, Polyspace does not consider this variable as a loop counter. For instance, in this example, the
float
type variableloopBreaker
is not considered as a loop counter and its use in breaking out of the loop does not result in a violation of the rule:float loopBreaker = 0.0f; /* No violation raised */ while(1) { if(loopBreaker > 5.0f) break; loopBreaker += 1.0f; }
When determining if a variable is a loop counter, Polyspace does not check whether the variable varies monotonically for the duration of the loop or whether the variable changes at each step of the loop.
Troubleshooting
If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
Group: Control Statement Expressions |
Category: Required |
AGC Category: Advisory |
Version History
See Also
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.