For Loop Never Executes
ID |
java.loop_never_executes |
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 condition already evaluates to false the first time it is checked, so the body never runs. Detection is deliberately narrow: it only fires when the counter is declared and initialised to an integer literal in the loop’s own init clause, and compared with <, ⇐, > or >= against another integer literal. A bound that comes from a field, a method call, or an expression is left alone.
Rationale
The loop’s body was written to run — whatever it does, from a validation check to a resource cleanup, it silently never happens, and the code around it reads as if it does. This is almost always a typo in the initial value or the comparison operator.
for (int retriesLeft = 0; retriesLeft < 0; retriesLeft++) { // never runs
attemptReconnect();
}
Remediation
Fix the initial value or the comparison so the condition can actually hold.
for (int retriesLeft = 0; retriesLeft < MAX_RETRIES; retriesLeft++) {
attemptReconnect();
}