I have a question in my mind. In many places I saw
int a=2;
if(2==a){
//Some operation
}
Can you tell me what is the advantage on comparing by 2==a
in place of a==2
.
I have a question in my mind. In many places I saw
int a=2;
if(2==a){
//Some operation
}
Can you tell me what is the advantage on comparing by 2==a
in place of a==2
.
Some people like to do that to force an error, rather than incorrect behaviour, if they accidentally typed =
instead of ==
. However:
so the only real purpose is to make the code confusing to read.
A better habit might be to declare all variables const
, unless you specifically want them to be mutable. That would also prevent accidental assignment, while making the code easier rather than harder to reason about.
This has became famous after the story mentioned in preface/introduction in the book Expert C Programming: Deep C Secrets By Peter van der Linden.There was $20 Million Bug related to this concept. So experts from this book
if (i=3)
instead of:
if (i==3)
Some programmers have developed the habit of writing the literal first, like this: if (3==i). Then, if an equal sign is accidentally left out, the compiler will complain about an"attempted assignment to literal." This won't protect you when comparing two variables, but every little bit helps.
In Spring 1993, in the Operating System development group at SunSoft, we had a "priority one" bug report come in describing a problem in the asynchronous I/O library. The bug was holding up the sale of $20 million worth of hardware to a customer who specifically needed the library functionality, so we were extremely motivated to find it. After some intensive debugging sessions, the problem was finally traced to a statement that read :
x==2;
It was a typo for what was intended to be an assignment statement. The programmer 's finger had bounced on the "equals" key, accidentally pressing it twice instead of once. The statement as written compared x to 2, generated true or false, and discarded the result .