Using the assignment operator in the outermost expression in a conditional expression of a selection statement (if or switch) or an iteration statement (while, do, or for) shall be diagnosed because this typically indicates programmer error and can result in unexpected behavior.
...
In this noncompliant code example, an assignment expression is the outermost expression in a conditional expressionan if statement.
| Code Block | ||
|---|---|---|
| ||
if (a = b) {
/* ... */
}
|
While this the intent of the code may be intendedindeed be to assign b to a and test the value of the result for equality to zero, it is almost always 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 . Consequently, making this coding error would typically be eliminated by adherence detectable by adhering to MSC00-C. Compile cleanly at high warning levels.
Compliant Solution
This When the assignment of b to a is not intended, this conditional block is now executed when a is equal to b.
| Code Block | ||
|---|---|---|
| ||
if (a == b) {
/* ... */
}
|
This When the assignment is, if fact, intended, this is an alternative compliant solution:
| Code Block | ||
|---|---|---|
| ||
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.
...