You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 4 Next »

Using the assignment operator in the outermost expression in a conditional expression shall be diagnosed because this typically indicates programmer error and can result in unexpected behavior.

Noncompliant Code Example

In this noncompliant code example, an assignment expression is the outermost expression in a conditional expression.

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

While this may be intended, it is almost always a case of the programmer mistakenly using the assignment operator = instead of the equals operator ==. Consequently, many compilers will warn about this condition. Consequently, this coding error would typically be eliminated by adherence to MSC00-C. Compile cleanly at high warning levels.

Compliant Solution

This conditional block is now executed when a is equal to b.

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

This is an alternative compliant solution:

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

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.

Risk Assessment

Errors of omission can result in unintended program flow.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

MSC02-C

low

likely

medium

P6

L2

Automated Detection

The LDRA tool suite Version 7.6.0 can detect violations of this recommendation???

GCC Compiler Version 4.4.0 can detect violations of this recommendation when the -Wall flag is used???

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

Klocwork Version 8.0.4.16 can detect violations of this rule with the ASSIGCOND.BOOL, ASSIGCOND.CALL, ASSIGCOND.GEN, and EFFECT checkers.

Related Vulnerabilities

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

Other Languages

This rule appears in the C++ Secure Coding Standard as EXP18-CPP. Do not perform assignments in conditional expressions.

Bibliography

[[Hatton 95]] Section 2.7.2, "Errors of omission and addition"
[[ISO/IEC PDTR 24772]] "KOA Likely Incorrect Expressions"
[[MITRE 07]] CWE ID 480, "Use of Incorrect Operator"

  • No labels