Java Reference
In-Depth Information
However, the loop never terminates. Successive values of i are 1, 3, 5, 7, 9, 11, 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, then 1, and
proceeds as described earlier.
Noncompliant Code Example
This noncompliant code example terminates but performs many more iterations than ex-
pected:
Click here to view code image
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 0. 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, ter-
minating the loop.
Compliant Solution
One solution is to simply ensure the loop termination condition is reached before the
counter inadvertently wraps.
Click here to view code image
for (i = 1; i == 11; i += 2) {
// ...
}
This solution can be fragile when one or more of the conditions affecting the iteration
must be changed. A better solution is to use a numerical comparison operator (that is, < ,
<= , > , or >= ) to terminate the loop.
Click here to view code image
Search WWH ::




Custom Search