Avoid Assignment In Loop Condition

ID

java.loop_assignment_in_while_condition

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

efficiency

Description

Reports while and do-while loops whose continuation condition contains an assignment expression.

Rationale

A condition like while x = read( > 0) folds two things into a single expression: a side-effect (the assignment) and the control-flow test. That makes the loop harder to scan visually and easy to misread as the equality check ==. It also spreads the state-update across the condition and the body, so reasoning about the value of x on each iteration requires tracing the side-effect first.

// Bad — assignment embedded in the condition
int line;
while ((line = read()) > 0) {
    process(line);
}

// Good — assignment explicit, condition expresses the test
int line = read();
while (line > 0) {
    process(line);
    line = read();
}

Remediation

Move the assignment out of the condition. Either initialize the loop variable before the loop and re-assign it at the end of the body, or convert the loop into a for with an explicit update section.