MISRA C:2023 Rule 14.1
Description
Rule Definition
A loop counter shall not have essentially floating type.
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 a variable used to exit the loop is outside the loop control expression, the checker does not consider it as a loop counter and does not include the variable in its checks. For instance, in this example, the variable
loopBreaker
is not considered as a loop counter: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, the checker does not check whether the variable varies monotonically for the duration 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
Introduced in R2024a