If a while
or for
statement uses a loop counter, and increments or decrements the counter by more than one, it must use an inequality 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. (See rule NUM00-J. Detect or prevent integer overflow.)
...
However, the loop never terminates; successive values of i
are 1, 3, 5, 7, 9, and 11, allowing the comparison with 10 to be skipped. The value reaches the maximum representable positive number (Integer.MAX_VALUE
), then 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.
...
This noncompliant code example terminates , but performs more iterations than expected.
...
Successive values of i
are 1, 6, and 11, skipping past 10. The value of i
then wraps from near the maximum positive value to near the lowest negative value and works its way up toward zero. It then assumes 2, 7, and 12, skipping past 10 again. After the value wraps from the high positive to the low negative side three more times, it finally reaches 0, 5, and 10, terminating the loop.
...
This usually happens when the step size is more than one1.
Compliant Solution
It is insufficient to compare with Integer.MAX_VALUE - 1
when the loop increment is greater than 1. To be compliant, ensure that the comparison is carried out with (Integer.MAX_VALUE
- minus the counter's value).
Code Block | ||
---|---|---|
| ||
for (i = 1; i <= Integer.MAX_VALUE - 2; i += 2) { // ... } |
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="9dee2badc91e3839-7987f9f1-49554810-a882ba5b-46fb0fa14f06e840580afda8"><ac:plain-text-body><![CDATA[ | [java:[JLS 2005 | AA. References#JLS 05]] | 15.20.1 Numerical Comparison Operators <, <=, >, and >= | ]]></ac:plain-text-body></ac:structured-macro> |
...
MSC55-J. Finish every set of statements associated with a case label with a break statement 49. Miscellaneous (MSC)