Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean equal: 0 == a, does operand order matter?

I saw some people wrote this Boolean equal in their code, I usually put constant at the right hand side of "==" operator. I notice 0 == a has faster operation than a == 0. Can someone explain why? And what's the best practice for it?

like image 832
9blue Avatar asked Jan 22 '26 15:01

9blue


2 Answers

It's a relic of the C/C++ world.

In C, the advantage of writing 0 == a vs. a == 0 is that you can't accidentally write a = 0 instead, which means something entirely different. Since 0 is an rvalue, 0 = a is illegal.

In Java that reasoning does not apply because a = 0 is illegal as well (since 0 is not boolean, a can't be boolean). It doesn't hurt though, so it really doesn't matter a lot which one to choose.

Performance has absolutely nothing to do with that.

like image 132
Niklas B. Avatar answered Jan 24 '26 06:01

Niklas B.


As other answers have described, the convention of putting constants to the left of == is to prevent programmer mistakes. It's called Yoda conditions (I'll expand on this at the end of the answer).

You talk about performance, so I suggest you view the bytecode:

a == 0

becomes:

   5: iload_1       
   6: ifne          13
   9: iconst_1      
  10: goto          14
  13: iconst_0      

and

0 == a

becomes:

  20: iload_1       
  21: ifne          28
  24: iconst_1      
  25: goto          29
  28: iconst_0   

In other words, the two are absolutely identical at the bytecode level, so there can't be a performance difference between them.

So it really comes down to readability. The principal purpose of conditions of the form int == var is to avoid mistakes like var = int (notice the single =), which would not test for equality but rather assign to var and return the value of the assignment. The value of the assignment is an integer, which in many programming languages can be used in a boolean context. In Java, however, an integer cannot be used in a boolean context, so you don't need to worry about mistakenly typing a single-equal instead of a double-equal, since it will be flagged by the compiler as an error. Therefore, you should prefer a == 0 in Java, and not the reverse which is slightly more convoluted and harder to read.

In fact, the Wikipedia article I linked to makes this statement:

Critics of Yoda conditions see the lack of readability as a disadvantage that does not outweigh the benefits described above. Some programming languages do not allow variable assignments within conditionals, so this error is impossible to make.

like image 22
arshajii Avatar answered Jan 24 '26 05:01

arshajii