为什么语句int null = 0, *p = null 是非法的?

Why the statement int null = 0, *p = null is illegal?

我是 C++ 的新手,正在尝试学习指针的概念。有人能告诉我为什么下面的 C++ 语句是非法的吗?在我看来是合法的,但有人告诉我这是非法的。

int null = 0, *p = null;

C++ 标准允许为指针分配值 0 作为常量。

然而,代码:

int null = 0;
int *p = null; 

不会将p设置为常量0,而是将其设置为null的值,这是一个整型变量。

如果我们稍微归纳一下,将 int null = 0; 放在一行,将 int *p = null; 放在完全不同的一行,中间插入一些代码。没有人说中间的代码不执行 null = 4; - 但是,我不认为这是不允许这样做的主要原因,而是编写一个检查 [= 的编译器更容易36=] 比 "is this named constant of the value zero"。如果常量来自另一个编译单元(link-time 常量)怎么办?

此外,阅读 0 比拥有 46 种不同的编码标准要容易得多,每个编码标准使用不同的名称 null

请注意,即使您使用 const int null = 0;,它仍然不是常量 0 - 它是一个与 0 具有相同值的常量,但在词法上不同,作为 0.

如果您尝试编译这段代码,您应该会收到以下错误:

error: cannot initialize a variable of type 'int *' with an lvalue of type 'int'

本质上,您正在尝试用变量初始化指针。 C++ 中唯一允许的是将指针直接分配给零。

int * p = 0;

像上面的例子一样可行。

要定义一个指针,您需要使用与符号 (&) 作为您传递的对象的前缀。

int null = 0, *p = &null;

这将修复 error: cannot initialize a variable of type 'int *' with an value of type 'int'