Versions Compared

Key

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

...

In this noncompliant code example, the controlling expression in the if statement is an assignment expression.:

Code Block
bgColor#FFcccc
public void f(boolean a, boolean b) {
  if (a = b) {
    /* ... */
  }
}

...

The conditional block shown in this compliant solution only executes when a is equal to b.:

Code Block
bgColor#ccccff
public void f(boolean a, boolean b) {
  if (a == b) {
    /* ... */
  }
}

...

When the assignment is intended, this compliant solution clarifies the programmer's intent.:

Code Block
bgColor#ccccff
public void f(boolean a, boolean b) {
  if ((a = b) == true) {
    /* ... */
  }
}

...

It may be clearer to express the logic as an explicit assignment followed by the if condition.:

Code Block
bgColor#ccccff
public void f(boolean a, boolean b) {
  a = b;
  if (a) {
    /* ... */
  }
}

...

In this noncompliant code example, an assignment expression appears as an operand of the && operator:

Code Block
bgColor#FFcccc
public void f(boolean a, boolean b, boolean flag) {
  while ( (a = b) && flag ) {
    /* ... */
  }
}

...

When the assignment of b to a is unintended, this conditional block is now executed only when a is equal to b and flag is true.:

Code Block
bgColor#ccccff
public void f(boolean a, boolean b, boolean flag) {
  while ( (a == b) && flag ) {
    /* ... */
  }
}

...

Exceptionally, it is permitted to use the assignment operator in conditional expressions when the assignment is not the controlling expression (that is, the assignment is a sub-expressionsubexpression), as shown in the following compliant solution.:

Code Block
bgColor#ccccff
public void assignNocontrol(BufferedReader reader) throws IOException{
  String line;
  while ((line = reader.readLine()) != null) {
    // ... work with line
  }
}

...