'a == null'和'null == a'之间的区别 [英] Difference between 'a == null' and 'null == a'

查看:145
本文介绍了'a == null'和'null == a'之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当检查变量是否为null时,我看到建议的编码样式是 if(null == a)。这和有什么区别if(a == null)

When checking to see if a variable is null, I have seen that the suggested coding style is if(null == a). What is the difference between this and if(a == null)?

推荐答案

没有。

由于历史原因,人们有时会写 null == a ,因为它消除了C中与拼写相关的错误的可能性。如果你要写:

People will sometimes write null == a for historical reasons, because it removes the possibility of a typo-related bug in C. If you were to write:

if (a = NULL) { // note, only single =
  ...

然后执行赋值语句 a = NULL ,语句的结果是赋值(即NULL)。因此,不是检查 a 的值,而是将其设置为NULL,然后基本上检查 if(NULL) ,这总是错误的。这编译,但几乎肯定不是你想要的。而这一切都归结于 = vs == 的小错字。

in C, then that would execute the assignment statement a = NULL, with the statement's result being the value assigned (ie, NULL). Thus, rather than checking a's value, you set it to be NULL and then checked essentially if (NULL), which is always false. This compiles, but is almost certainly not what you want. And it's all due to a small typo of = vs ==.

如果先放 NULL ,那么 if(NULL = a)是编译错误,因为你不能为NULL所代表的常量赋值。

If you put the NULL first, then if (NULL = a) is a compilation error, since you can't assign a value to the constant that NULL represents.

在Java中,没有必要这样做,因为 if(null) {... 无法编译。 (您可以在Java中仍然存在与布尔变量相同的错误: if(someBooleanVar = someMethod())。但这是一种相对罕见的模式。 )

In Java, there's no need for this, since if (null) {... doesn't compile. (You can still have the same bug in Java with boolean variables: if (someBooleanVar = someMethod()). But that's a relatively rare pattern.)

这种风格有时被称为

This style is sometimes referred to as "Yoda conditions," since it's reminiscent of Yoda's quirky speaking style in Star Wars.

这篇关于'a == null'和'null == a'之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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