Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Wiki Markup
If a {{while}} or {{for}} statement uses a loop counter, and increments or decrements it by more than one, it should use a numerical comparison operator (that is, {{<}}, {{<=}}, {{>}}, or {{>=}}) to terminate the loop. This prevents the loop from executing indefinitely or until the counter wraps around and reaches the final value (\[[INT00-J. Perform explicit range checking to ensure integer operations do not overflow]\]).

...

This noncompliant code example appears to iterate five times. However, the loop never terminates because the successive values of i are 1, 3, 5, 7, 9 and 11, allowing the comparison with 10 to be skipped. On a Java based system, the The value reaches the maximum representable positive number (Integer.MAX_VALUE) and on subsequent incrementing, wraps to the second lowest negative number (Integer.MIN_VALUE + 1). It then works its way up to -1, then 1, and proceeds as described earlier.

...

Code Block
bgColor#FFCCCC
for (i = 1; i <= Integer.MAX_VALUE; i += 2) {
  // ...
}

Compliant Solution

It is not sufficient insufficient to compare with Integer.MAX_VALUE - 1 when the loop counter is more than 1. To be safecompliant, ensure that the comparison is carried out with (Integer.MAX_VALUE - counter's value).

...