...
This noncompliant code example appears to iterate five times.:
Code Block | ||
---|---|---|
| ||
for (i = 1; i != 10; i += 2) { // ... } |
However, the loop never terminates! Successive values of i
are 1, 3, 5, 7, 9, 11, etc.and so on; the comparison with 10 never evaluates to true
. 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–1, then 1, and proceeds as described earlier.
...
This noncompliant code example terminates but performs more iterations than expected.:
Code Block | ||
---|---|---|
| ||
for (i = 1; i != 10; i += 5) { // ... } |
Successive values of i
are 1, 6, and 11, skipping 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 zero0. It then assumes 2, 7, and 12, skipping 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.
...
Using a numerical comparison operator guarantees proper loop termination.:
Code Block | ||
---|---|---|
| ||
for (i = 1; i <= 10; i += 2) { // ... } |
...
Numerical comparison operators fail to ensure loop termination when comparing with Integer.MAX_VALUE
or Integer.MIN_VALUE
.:
Code Block | ||
---|---|---|
| ||
for (i = 1; i <= Integer.MAX_VALUE; i += 2) { // ... } |
...
It is also 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 step's value).:
Code Block | ||
---|---|---|
| ||
for (i = 1; i <= Integer.MAX_VALUE - 2; i += 2) { // ... } |
...
Related Guidelines
CWE-835, " Loop with Unreachable Exit Condition ('Infinite Loop')" unreachable exit condition ("infinite loop") |
Bibliography
...