c++ - 这些是空指针,还是指向地址 0 的指针?

标签 c++ c null language-lawyer nullptr

如果我写

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?

p1p2p3 中的哪一个(edit:我添加了 p8p9) 将是 空指针(即 == NULL,可能是地址零,也可能不是地址零),它们中的哪一个会是地址为零的指针(可能是也可能不是== NULL)?

如果 C 和 C++ 的答案不同,它们各自的答案是什么?

最佳答案

并且用 C 来完成安迪的答案:

From the C99 Standard :

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 type void *, 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 指针。实际上,在您的示例中,除了 p4p8p9 之外的所有指针都是空指针。 p4p8p9 不必是空指针,因为它们的初始化不是常量表达式,因为它包含变量(即使 const 合格)。

Here's another answer about NULL in C++ , 记录在案。

关于c++ - 这些是空指针,还是指向地址 0 的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16563114/

相关文章:

c++ - 为什么我们需要对字符串使用标准库,而不对int数据类型使用?

c++ - 需要一些修复 SurfaceArea 和 LateralArea

c - 如何在gtk上的按钮信号中添加计时器?

c - 为什么我的数组大小在 C 中不是 4 字节

ios: self 在 block 中变为零?

c++ - 在if语句C++中意外中断

名称正确,但是 "dereferencing pointer to incomplete type"

java - 处理无效 REST API 参数的内部 Java 代码最佳实践

java - Android 开发初学者指南 [第 5 章] 中的 NullPointerException

c++ - 在 Mac 上使用 PJSIP 进行回声消除