Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

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
bgColor#ccccff
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
bgColor#ccccff
String line;
BufferedReader reader = // initialize
while ((line = reader.readLine()) != null) {
  // ... work with line
}

Related Guidelines

ISO/IEC TR 24772:20102013

"Likely Incorrect Expression [KOA]"

MITRE CWE

CWE ID 480, " Use of Incorrect Operator"incorrect operator

Bibliography

[Hatton 1995]

Section 2.7.2, "Errors of omission Omission and additionAddition"

 

...