CERT-FLP30-C_b
Synopsis
Do not use floating-point variables as loop counters
Enabled by default
Yes
Severity/Certainty
Low/Medium

Full description
Because floating-point numbers represent real numbers, it is often mistakenly assumed that they can represent any simple fraction exactly. Floating-point numbers are subject to representational limitations just as integers are, and binary floating-point numbers cannot represent all real numbers exactly, even if they can be represented in a small number of decimal digits. This check is identical to MISRAC2012-Rule-14.1_b.
Coding standards
- CERT FLP30-C
Do not use floating point variables as loop counters
- MISRA C:2012 Rule-14.1
(Required) A loop counter shall not have essentially floating type
Code examples
The following code example fails the check and will give a warning:
void func(void) {
for (float x = 0.1f; x <= 1.0f; x += 0.1f) {
/* Loop may iterate 9 or 10 times */
}
}
The following code example passes the check and will not give a warning about this issue:
#include <stddef.h>
void func(void) {
for (size_t count = 1; count <= 10; ++count) {
float x = count / 10.0f;
/* Loop iterates exactly 10 times */
}
}