Assigning a value inside a condition (of an if
statement, a for
statement, a while
, or a
switch
) can be confusing. It assigns the value and checks it at the same time, but it is easily confused with a simple equality check
with ==
and the original intention can be unclear.
if (x = getValue()) { // Noncompliant: assigning and checking. Is it on purpose?
doSomething();
}
It is better to assign before the statement and use the condition for the check only:
x = getValue();
if (x) {
doSomething();
}
Exceptions
This rule ignores assignments explicitly enclosed in parentheses.
while ((run = keepRunning())) {
//...
}