Possible Duplicate:
Order of condition checking?
When i read some source codes, the if statement is coded in this way,
if (1 == a) {
...
}
instead of
if (a == 1){
...
}
I read a programming book about the advantage of this way, but cannot remember exactly what it is about. Any one know about this ?
(Sorry if this question disturbs you 🙂 )
The advantage is compiler will tell you that error right away. For example,
a = 1will compile but will produce an error at run time whereas1 = awill produce an error at compile time since1is not a valid lvalue.Example: this will produce an error right away:
Whereas this will compile (warnings may be produced depending on the compiler) but it will cause issues at run time.
The main idea here is to make certain that you are using
==in a condition instead of=.That being said every modern compiler (ie. Eclipse) will treat the above as an error now. So it’s not as big of a deal as it used to back in the notepad and vi days (in my opinion). I personally prefer the
a == 1since that seems more readable to me.