布尔等于:0 == a,操作数顺序重要吗? [英] Boolean equal: 0 == a, does operand order matter?

查看:95
本文介绍了布尔等于:0 == a,操作数顺序重要吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到有人在他们的代码中写了这个布尔等值,我通常在"=="运算符的右侧放置常量.我注意到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 == aa == 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆