Do not use the assignment operator in conditional expressions because it frequently indicates programmer error and can result in unexpected behavior. This means that the assignment operator should not be used in the following contexts:
- if
if
(controlling expression) while
(controlling expression)do ... while
(controlling expression)for
(second operand)switch
(controlling expression)?:
(first operand)&&
(either operand)||
(either operand)?:
(second or third operands) where the ternary expression is used in any of these contexts
...
When the assignment of b
to a
is unintended, this conditional block is now executed when a
is equal to b
.:
Code Block | ||
---|---|---|
| ||
public void f(boolean a, boolean b) { if (a == b) { /* ... */ } } |
...
Exceptionally, it is permitted to use the assignment operator in conditional expressions if the assignment is not the controlling expression (that is, the assignment is a subexpression), as shown in the following compliant example: (That is, the assignment is a sub-expression.)
Code Block | ||
---|---|---|
| ||
String line; BufferedReader reader = // initialize while ((line = reader.readLine()) != null) { // ... work with line } |
Related Guidelines
"Likely Incorrect Expression [KOA]" | |
CWE ID 480, " Use of Incorrect Operator"incorrect operator |
Bibliography
Section 2.7.2, "Errors of omission Omission and additionAddition" |
...