Rule Definition
When using a floating-point loop counter, the accumulation of rounding errors may result in a mismatch between the expected and actual number of iterations. This 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.
Even if a loop with a floating-point loop counter appears to behave correctly on one implementation, it may give a different number of iterations on another implementation.
Remediation
Use an integral variable
Violation Code Sample
uint32_t counter = 0u;
for ( float32_t f = 0.0f; f < 1.0f; f += 0.001f )
{
++counter;
}
/*The following while loop is non-compliant because f is being used as a loop counter. */
float32_t f = 0.0f;
while ( f < 1.0f )
{
f += 0.001f;
}
Fixed Code Sample
float32_t f;
for ( uint32_t counter = 0u; counter < 1000u; ++counter )
{
f = ( float32_t ) counter * 0.001f;
}
_______________________________________________
/* The following while loop is compliant because f is not being used as a loop counter.*/
float32_t f;
uint32_t u32a;
f = read_float32 ( );
do
{
u32a = read_u32 ( );
/* f does not change in the loop so cannot be a loop counter */
} while ( ( ( float32_t ) u32a - f ) > 10.0f );
Reference
MISRA C 2012 - 14.1: A loop counter shall not have essentially floating type
AUTOSAR, C++, 2014, Rule A6-5-2: A for loop shall contain a single loop-counter which shall not have floating point type.
MISRA, C++, 2008, Rule 6-5-1: A for loop shall contain a single loop-counter which shall not have floating type.
Related Technologies
Technical Criterion
Complexity - Algorithmic and Control Structure Complexity
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.