Versions Compared

Key

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

Do not use the assignment operator in the outermost expression of an if or switch statement or a looping statement (while, do, or for) because this it typically indicates programmer error and can result in unexpected behavior.

...

Code Block
bgColor#FFcccc
public void exampleFunction(Object a, Object b){

  if (a = b) {
    /* ... */
  }

}

While Although the intent of the code could be to assign b to a and test the value of the result for equality to zero, it is frequently a case of the programmer mistakenly using the assignment operator = instead of the equals operator ==.

...

Code Block
bgColor#ccccff
public void exampleFunction(Object a, Object b){


  if ((a = b) == true) {
    /* ... */
  }

}

Although But it could might be preferable to express this same logic as an assignment followed by a conditional:

...

CERT C Secure Coding Standard

EXP18-C. Do not perform assignments in selection statements

CERT C++ Secure Coding Standard

EXP19-CPP. Do not perform assignments in conditional expressions

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="6854cf1ba87adc31-e6f38c6a-428544b4-ba8f9a88-b8b1ff4fe985091911c4a7d1"><ac:plain-text-body><![CDATA[

[ISO/IEC TR 24772:2010

http://www.aitcnet.org/isai/]

"Likely Incorrect Expression [java:KOA]"

]]></ac:plain-text-body></ac:structured-macro>

MITRE CWE

CWE ID 480, "Use of Incorrect Operator"

...

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="63d59514c28e7db3-32fcd49a-4f804d8e-b8d5b8a6-90aad8de2a100bd722615e35"><ac:plain-text-body><![CDATA[

[java:[Hatton 1995

AA. References#Hatton 95]]

Section 2.7.2, "Errors of omission and addition"

]]></ac:plain-text-body></ac:structured-macro>

...