For Loop Counter Not Advanced
ID |
java.loop_var_never_changed |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
control-flow, loop, reliability |
Description
Reports a classic for loop whose single init variable is tested in the condition but is never advanced anywhere in the loop: not in the update clause, not in the condition, and not in the body either.
Rationale
A for loop’s whole point is to advance its counter towards the bound its condition tests. When nothing in the loop — neither the update clause, nor the condition, nor the body — ever changes the counter, the loop only terminates if something else breaks out of it. The most common cause is an edited loop header where the counter was renamed in the declaration and the condition but the update clause was left referring to the old name.
// Bad -- the update clause advances a different variable than the one the condition tests
for (int attempt = 0; attempt < maxAttempts; successes++) {
tryOnce();
}
Advancing the counter inside the body instead of the update clause is untidy but legal, so it does not get reported — the defect here is the counter never being advanced at all, not the style of where it happens.
Remediation
Advance the same variable the condition tests, in the update clause.
// Good
for (int attempt = 0; attempt < maxAttempts; attempt++) {
tryOnce();
}