>
>
>
V6108. Do not use real-type variables i…


V6108. Do not use real-type variables in 'for' loop counters.

The analyzer has detected a real-type variable as the 'for' loop counters. Since floating-point numbers cannot accurately represent all real numbers, using such variables in a loop can lead to unexpected results, e.g. redundant iterations.

Let's take a closer look:

for (double i = 0.0; i < 1.0; i += 0.1) {
    ....
}

The number of iterations in this loop will be 11 instead of the expected 10. When executing code without the 'strictfp' modifier in Java versions earlier than 17, the result of floating-point operations may also be platform-dependent. To avoid possible issues, it is better to use a counter of the integer type and perform calculations inside the loop body:

for (var i = 0; i < 10; i++) {
    double counter = i / 10.0;
    ....
}

Another reason to avoid using a real type is the danger of an infinite loop. Look at the following example:

for (float i = 100000000.0f; i <= 100000009.0f; i += 0.5f) {
    ....
}

It occurs because the increment is too small relative to the number of significant figures. To prevent this, it is better to use an integer-type counter, and to avoid precision loss, use 'double' to store the value:

for (var i = 0; i < 19; i++) {
    double value = 100000000.0d + i / 2d;
    ....
}

This diagnostic is classified as: