为什么C ++编译器接受此初始化?静态整数x = x; [英] Why is this initialization accepted by the c++ compiler? static int x = x;

查看:75
本文介绍了为什么C ++编译器接受此初始化?静态整数x = x;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚发现以下内容:

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.

这篇关于为什么C ++编译器接受此初始化?静态整数x = x;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆