For Loop Without Init/Update Should Be While
ID |
java.for_without_init_update_prefer_while |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code smell |
Language |
Java |
Tags |
code-style |
Description
Reports for loops that have no initialization and no update clauses but do have a condition, such as for (; cond; ) { … }. This construct is semantically equivalent to while (cond) { … } and should use the simpler form.
Rationale
A for loop communicates a counting or stepping pattern: initialize, test, update. When both the init and update parts are empty, the for keyword misleads readers into expecting those components. Using while makes the intent clearer:
// Bad - for with only a condition is a disguised while
int i = 0;
for (; i < 10; ) {
process(i);
i++;
}
Note: the intentional infinite loop for (;;) is not flagged because it is a well-established Java idiom.