布尔等于:0 == a,操作数顺序重要吗? [英] Boolean equal: 0 == a, does operand order matter?
问题描述
我看到有人在他们的代码中写了这个布尔等值,我通常在"=="运算符的右侧放置常量.我注意到0 == a的操作比a == 0的操作快.有人可以解释为什么吗?最佳做法是什么?
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?
推荐答案
它是C/C ++世界的遗物.
It's a relic of the C/C++ world.
在C语言中,编写0 == a
与a == 0
的优点在于,您不能意外地编写a = 0
,这意味着完全不同.由于0
是右值,所以0 = a
是非法的.
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.
在Java中,推理也不适用,因为a = 0
也是非法的(因为0
不是布尔值,所以a
不能是布尔值).但这并没有什么坏处,所以选择哪一个并不重要.
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.
性能绝对与此无关.
这篇关于布尔等于:0 == a,操作数顺序重要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!