Comparing literal and variable
suggest changeSuppose you are comparing a variable with a constant:
if (i == 2) /* Easy to mistype as =. */
{
do_something();
}
If == is mistyped as =, the assignment is valid when the left operand is a modifiable lvalue, and the bug can be hard to see.
if (2 == i) /* Assignment to 2 will not compile. */
{
do_something();
}
If one = is left out, the compiler diagnoses an assignment to a non-lvalue. This does not help when both sides are modifiable lvalues. Many style guides reject this "Yoda" order because it is harder to read; a compiler warning for = inside a condition is usually the better safeguard.
See here for more info.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents