如果我写
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
中的哪一个(edit:我添加了 p8
和 p9
) 将是 空指针(即 == NULL
,可能是地址零,也可能不是地址零),它们中的哪一个会是地址为零的指针(可能是也可能不是== NULL
)?
如果 C 和 C++ 的答案不同,它们各自的答案是什么?
最佳答案
并且用 C 来完成安迪的答案:
6.3.2.3 Pointers
1 A pointer to void may be converted to or from a pointer to any incomplete or object type. A pointer to any incomplete or object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.
3 An integer constant expression with the value
0
, or such an expression cast to typevoid *
, is called a null pointer constant. 55) If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.
因此,任何计算结果为 0
的 整数常量表达式 都是空指针常量,并且可以转换为 NULL
指针。实际上,在您的示例中,除了 p4
、p8
和 p9
之外的所有指针都是空指针。 p4
、p8
和 p9
不必是空指针,因为它们的初始化不是常量表达式,因为它包含变量(即使 const
合格)。
关于c++ - 这些是空指针,还是指向地址 0 的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16563114/