Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: new rule

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

...

While the intent of the code may be to assign b to a and test the value of the result for equality to zero, it is very frequently a case of the programmer mistakenly using the assignment operator = instead of the equals operator ==. Consequently, many compilers will warn about this condition making this coding error detectable by adhering to recommendation MSC00-C. Compile cleanly at high warning levels.

Compliant Solution

When the assignment of b to a is not intended, this conditional block is now executed when a is equal to b.

...

Code Block
bgColor#ccccff
if ((a = b) !== 0true) {
  /* ... */
}

It is less desirable in general, depending on what was intended because it mixes the assignment in the condition, but it is clear that the programmer intended the assignment to occur.

...

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

EXP18 EXP04-C J

low

likely

medium

P6

L2

Automated Detection

Tool

Version

Checker

Description

Section

LDRA tool suite

Include Page
java:LDRA_Vjava:LDRA_V

 

 

Section

GCC

Include Page
java:GCC_Vjava:GCC_V

 

section

can detect violations of this recommendation when the -Wall flag is used.

Section

Compass/ROSE

 

 

Section

could detect violations of this recommendation by identifying any assignment expression as the top-level expression in an if or while statement.

Section

Klocwork

Include Page
java:Klocwork_Vjava:Klocwork_V
Section

ASSIGCOND.GEN ASSIGCOND.CALL

 

Related

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

CERT C++ Secure Coding Standard: EXP19-CPP. Do not perform assignments in conditional expressions
CERT C Secure Coding Standard: EXP18-C. Do not perform assignments in conditional expressions

...