-2

I've always wondered why some programmers use FALSE == var rather than var == FALSE in conditionals. IS there any performance gain in using the former? The latter format is more readable, I believe.

afaolek
  • 8,452
  • 13
  • 45
  • 60
  • No performance difference, but not compiled if written "FALSE = var" by mistake. Looks ugly. – Alex F May 07 '14 at 08:34
  • 3
    Specify which language. But in all the languages that I know, there's no difference. It's called [Yoda Conditions](http://en.wikipedia.org/wiki/Yoda_conditions), some people use it to avoid accidentally using `=` instead of `==`. – Yu Hao May 07 '14 at 08:36
  • [Related question](http://stackoverflow.com/questions/4957770/conditional-statements-difference) you may see. – Daniel Daranas May 07 '14 at 08:39
  • possible duplicate of [Checking for null - what order?](http://stackoverflow.com/questions/10983573/checking-for-null-what-order) – GuyT May 07 '14 at 08:39

3 Answers3

2

This is simply to avoid the frequent error of accidentally typing var = FALSE instead of var == FALSE, thus assigning FALSE to the var and guaranteeing that the condition be true.

Sergey
  • 196
  • 1
  • 5
2

Some languages allow assignment where a condition is expected (C, for instance);

if (a = 5)

This led (at one point) to a common class of bugs, because of course the above assigns 5 to a and then, since 5 is not zero, goes into the body of the if. What the author meant, of course, was

if (a == 5)

If you write it the other way, the code can't be compiled:

if (5 = a)

...since you can't assign to a constant. So that flags up the bug and you fix it to

if (5 == a)

With any modern (or even relatively old) compiler, there's no need to do this. Use lint settings that warn you about assignments where comparisons are expected.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • I'm sure i read somewhere that where comparing like: var == FALSE is faster comparison rather than FALSE== var .T.J Answer will do more clear about this. – Aman May 07 '14 at 08:43
  • 1
    @Aman: No, it's no faster in any environment I've ever heard of. Both sides of the operator must still be evaluated, and the resulting values must be compared, regardless of which way you write it. – T.J. Crowder May 07 '14 at 08:58
0

No difference in meaning or performance there is.

Just avoiding the accidental var = FALSE assignment in case they make a typo programmers who use this style are.

Yoda conditions some people call them. Recommend them I do not. But if useful you find them, use them you may.

Daniel Daranas
  • 22,454
  • 9
  • 63
  • 116