For Loop Counter Moves The Wrong Way
ID |
java.for_bad_increment |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
reliability |
Description
Reports a classic for loop whose update clause steps the counter away from the bound tested in
the condition, for example for (int i = 10; i > 0; i++). The counter needs to approach the
bound to end the loop; stepping away from it does the opposite.
Rationale
When the counter moves the wrong way, the condition can never become false by getting closer to it. In practice the loop either runs until the counter overflows and wraps around — which can take billions of iterations — or, if it starts on the wrong side of the bound, never runs a single iteration at all. Neither outcome is what a reader expects from the loop header.
// Bad -- i grows away from 0, the loop keeps going long after "> 0" should have stopped it
for (int i = 10; i > 0; i++) {
System.out.println(i);
}
Remediation
Change the update clause to step toward the bound instead of away from it.
// Good -- i shrinks toward 0, matching the "> 0" condition
for (int i = 10; i > 0; i--) {
System.out.println(i);
}