Why is this initialization accepted by the c++ compiler? static int x = x;(为什么 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;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 c++ 编译器接受这个初始化?静态整数 x = x;
基础教程推荐
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 从 std::cin 读取密码 2021-01-01