【发布时间】:2013-05-09 21:51:29
【问题描述】:
如果我写
int zero = 0;
void *p1 = (void *)0;
void *p2 = (void *)(int)0;
void *p3 = (void *)(0 /*no-op, but does it affect the next zero?*/, 0);
void *p4 = (void *)zero; // For reference, this is a pointer to address zero
void *p5 = 0; // For reference, this is a null pointer
void *p6 = NULL; // For reference, this is a null pointer
void *p7 = nullptr; // For reference, this is a null pointer (C++11)
static const int static_zero_1 = 0; // Is this a literal zero when used?
static const int static_zero_2 = 1 - 1; // No "literals 0" per se... is it?
void *p8 = (void *)static_zero_1; // I have seen weird substitution rules...
void *p9 = (void *)static_zero_2; // do they apply for NULL too?
p1、p2 和 p3(编辑:我添加了 p8 和 p9)中的哪一个将是 空指针(即== NULL,可能是地址零,也可能不是),其中哪些是地址为零的指针(可能是== NULL,也可能不是== NULL)?
如果 C 和 C++ 的答案不同,它们各自的答案是什么?
【问题讨论】:
-
空指针不就是“指向地址0”定义的吗?
-
@leemes:不,见this answer。
-
@Andrew:我的意思是写我写的——你确定那也是 nullptr 吗?我的理解是它不是,因为它没有使用文字 0。
-
@Andrew 不要再猜测 Mehrdad - 他比那更聪明。
-
@Mehrdad 不,我的意思是
0和(0, 0)会有所不同,因为后者不是文字。幸运的是,我错了,事实并非如此 - 请参阅我的答案。
标签: c++ c null language-lawyer nullptr