I heard some programmers use if(1 == var) instead of if(var == 1) to avoid unintended assignment. Why or in what cases does it cause unintended assignment?
I heard some programmers use if(1 == var) instead of if(var == 1) to
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The problem is if you mistype the statement:
vs
In the first case, the code after the
ifis executed unconditionally (with no more than a warning from the compiler, which isn’t obliged to produce a warning for you — but the good ones do; if you aren’t using a good compiler, get one!). In the second case, you get a syntax error at compile time, so the problem has to be fixed before the code can compile.The problem isn’t always as blatant:
never executes the code after the
if, of course. Often though, you’ll have:and it won’t be clear whether you intended to assign or compare. You can make it clear to the compiler and code readers (humans) by writing:
or
I don’t use the ‘back-to-front’ comparison technique. I dislike the inverted conditions because they almost invariably read ‘wrong’ to me. I’m not comparing 1 with my variable; I’m comparing my variable with 1. So, even though logically the
==operator is commutative, I don’t think commutatively and prefer that ‘riskier’ way. I have not found myself making the assignment vs equality mistake often enough for the issue to be a problem. The compiler warns me if I do make a mistake (and I pay attention to the warning and fix the code so that there isn’t a problem).