C Interview Questions and Answers

 

Why do some people write if(0 == x) instead of if(x == 0)?

It's a trick to guard against the common error of writing



if(x = 0)



If you're in the habit of writing the constant before the ==, the compiler
will complain if you accidentally type



if(0 = x)



Evidently it can be easier for some people to remember to reverse the test than
to remember to type the doubled = sign. (To be sure, accidentally using = instead
of == is a typo which even the most experienced C programmer can make.)



On the other hand, some people find these reversed tests ugly or distracting, and
argue that a compiler should warn about if(x = 0). (In fact, many compilers do warn
about assignments in conditionals, though you can always write if((x = expression))
or if((x = expression) != 0) if you really mean it.)

Posted by:Richards