问题描述
简单问题:
是 if(pointerVar)
与 if pointerVar!= NULL)
?
此外, if(!pointerVar)
与相同if(pointerVar == NULL)
?
给我最技术上正确/这两个语句似乎和有意义的操作相同。
对于最迂回的答案,这里是相关的
首先,如果
语句工作,从& p>
但是指针如何转换为 bool
s?你可以问。好的,这里是&; 4.12.1:: - )
这意味着语句
if(ptr)
>
if((bool)ptr)
这等价于
if(ptr == NULL)
但
如果(!ptr)
好吧,C ++ spec和5.3.1.8说, p>
p>
if(!ptr)
b $ b
等同于
if(!(bool)ptr)
这等同于
if(!(ptr == NULL))
这最终相当于
if(ptr!= NULL)
$ b b
哇!这是一个有趣的搜索。希望这回答你的问题!
当然,这个故事还有更多。 NULL
不是C ++语言的一部分;它是< cstddef>
中的一个宏定义为
#define NULL 0
这样做是因为C ++标准在§ 4.10.1中定义了空指针
更正确,我应该使用数字字面值0在上面的例子。但是,如果你包含< cstddef>
,那么在预处理之后,这个代码就会生成相同的代码。
Simple question:
Is if (pointerVar)
the same as if (pointerVar!=NULL)
?
Also, is if (!pointerVar)
the same as if (pointerVar==NULL)
?
Give me your most technically correct/pedantic answer. The two statements seem and make sense to operate the same. Is there anything wrong with the former though (besides its slightly lower readability)?
解决方案 For the most pedantic answer, here's the relevant sections of the spec.
First, here's how if
statements work, from §6.4.4:
"But how are pointers converted to bool
s?" you may ask. Well, here's §4.12.1: :-)
So this means that the statement
if (ptr)
is equivalent to
if ((bool) ptr)
which is in turn equivalent to
if (ptr == NULL)
But what about
if (!ptr)
Well, the C++ spec, §5.3.1.8, says that
So this means that
if (!ptr)
is equivalent to
if (!(bool)ptr)
which is in turn equivalent to
if (!(ptr == NULL))
which is finally equivalent to
if (ptr != NULL)
Whew! That was a fun search to do. Hope this answers your question!
Of course, there is more to this story. NULL
is not part of the C++ language; it's a macro in <cstddef>
defined as
#define NULL 0
This works because the C++ standard defines the null pointer in §4.10.1 as
So to be more correct, I should have been using the numeric literal 0 in the above examples. However, if you have <cstddef>
included, then this works out to the same code after preprocessing.
这篇关于是if(pointerVar)和if(pointerVar!= NULL)一样吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!