...
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.
Noncompliant Code Example
In this noncompliant example, the expression x = y is used as the controlling expression of the while statement.
Code Block | ||||
---|---|---|---|---|
| ||||
do { /* ... */ } while ( foo(), x = y ) ; |
Compliant Solution
When the assignment of y to x is not intended, this conditional block is now executed when x is equal to y.
Code Block | ||||
---|---|---|---|---|
| ||||
do { /* ... */ } while ( foo(), x == y ) ;
|
When the assignment is intended, the following is an alternative compliant solution:
Code Block | ||||
---|---|---|---|---|
| ||||
do { /* ... */ } while ( foo(), (x = y) != 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.
Compliant Example
In this compliant example,the expression x = y is not used as the controlling expression of the while statement.
Code Block | ||||
---|---|---|---|---|
| ||||
do { /* ... */ } while ( x = y, p == q ) ;
|
Exceptions
Assignment can be used where the result of the assignment is itself a parameter to a comparison expression or relational expression
Code Block bgColor #ccccff lang c if ( ( x = y ) != 0 ) { /* ... */ }
- Assignment can be used where the expression consists of a single primary expression
Risk Assessment
Errors of omission can result in unintended program flow.
...
CERT C++ Secure Coding Standard | EXP19-CPP. Do not perform assignments in conditional expressions |
---|---|
CERT Oracle Secure Coding Standard for Java | EXP51-JG. Do not perform assignments in conditional expressions |
ISO/IEC TR 24772 | Likely incorrect expression [KOA] |
MITRE CWE | CWE-480, Use of incorrect operator |
ISO/IEC TR 17961 (Draft) | No assignment in conditional expressions [boolasgn] |
Bibliography
[Hatton 1995] | Section 2.7.2, "Errors of Omission and Addition" |
---|
...