Assignments within sub-expressions are hard to spot and therefore make the code less readable. Ideally, sub-expressions should not have
side-effects.
Noncompliant Code Example
if ($val = value() && check()) { // Noncompliant
}
Compliant Solution
$val = value();
if ($val && check()) {
}
or
if ($val == value() && check()) { // Perhaps in fact the assignment operator was expected
}
Exceptions
Assignments in while statement conditions, and assignments enclosed in relational expressions are allowed.
while (($line = next_line()) != NULL) {...}
while ($line = next_line()) {...}
See
- MISRA C:2004, 13.1 - Assignment operators shall not be used in expressions that yield a Boolean value
- MISRA C++:2008, 6-2-1 - Assignment operators shall not be used in sub-expressions
- MISRA C:2012, 13.4 - The result of an assignment operator should not be used
- MITRE, CWE-481 - Assigning instead of Comparing
- CERT, EXP45-C. - Do not perform assignments in selection statements
- CERT, EXP51-J. - Do not perform assignments in conditional expressions
- CERT, EXP19-CPP. - Do not perform assignments in conditional expressions