Loop Control Variable Reassigned in Body

ID

java.loop_control_var_reassigned_in_body

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

reliability

Description

Reports for-loop control variables that are reassigned inside the loop body.

Rationale

A for loop declares its iteration logic in the header: for (init; condition; update). When the loop variable is also modified inside the body, the iteration becomes non-obvious and hard to reason about. This is a common source of off-by-one errors, infinite loops, or skipped iterations.

// Bad -- loop variable modified in body
for (int i = 0; i < 100; i++) {
    i += 3;   // skips iterations unpredictably
    sum += i;
}

Remediation

Rewrite the loop so that the iteration variable is only advanced by the for-header update expression. If the iteration pattern does not fit the standard for form, consider using a while loop instead:

// Good -- only the for-header advances i
for (int i = 0; i < 100; i += 4) {
    sum += i;
}