为什么 c++ 编译器接受这个初始化?静态整数 x = x;

2022-01-19 00:00:00 initialization static c++

我刚刚发现了这个:

static int x = x;

为什么 C++ 编译器会接受这种初始化?

Why is this initialization accepted by the C++ compiler?

我会称之为编译器异常,但有人可能会对此给出一个很好的解释.

I would call it a compiler anomaly, but someone might come with a good explanation for this.

因此,对于具有静态存储的数据,可以使用自身初始化变量...我已经使用 VS2015 和 VS2017 编译器以及其他一些在线 C++ 编译器进行了尝试.

So for data with static storage, it is possible to initialize a variable with itself... I've tried this with a VS2015 and VS2017 compiler and also some other online C++ compilers.

推荐答案

static和非static变量其实是一样的.

It's actually the same for static and non-static variables.

名称在其声明符之后和初始化之前立即可见(如果有的话).因此在

A name becomes visible immediately after its declarator and before its initialization, if any. Thus in

static int x = x;

名称 x 在其第一次出现后立即变得可见,并且可以在初始化程序中引用.因为它是静态的,所以它的初始值是很好定义的(它是0).

the name x becomes visible immediately after its first occurrence, and can be referred to in the initializer. Since it's static, its initial value is well defined (it's 0).

这也是合法的,即使在块范围内:

This is also legal, even at block scope:

int x = x;

尽管在这里您可能会收到警告,因为 x 正在使用其自己的不确定值进行初始化(在大多数情况下行为未定义).

although here you're likely to get a warning because x is being initialized with its own indeterminate value (the behavior is undefined in most cases).

这是一件很愚蠢的事情,但 C++ 并不会特意阻止你做愚蠢的事情.例如,您可能想要声明一个指向自身的指针:

It's a silly thing to do, but C++ isn't in the business of going out of its way to prevent you from doing silly things. As an example, you might want to declare a pointer that points to itself:

void *p = (void*)&p;

这里初始化器指的是 p 的地址而不是它的值,但名称 p 必须是可见的才能使其工作.添加特殊情况规则被认为不值得.

Here the initializer refers to the address of p rather than its value, but the name p has to be visible to make that work. It wasn't considered worthwhile to add a special-case rule.

相关文章