[英]why local variable doesn't hide the global variable in array definition
I am reviewing subtle points in C++ these days. 我现在正在回顾C ++中的微妙观点。 I found an interesting question.
我发现了一个有趣的问题。 Could you please check it and share your reasoning why it works like that.
你可以检查一下,并分享你为什么这样工作的原因。
Thank you 谢谢
const int x = 5;
void func() {
// ! Error
// int x = x;
// ! Fine
int x[x];
x[0] = 12;
cout << x[0];
}
The point of declaration for a variable (that is, the point at which the name assumes the meaning given to it by the declaration, hiding any other entities with the same name in a wider scope) comes after the declarator, and before any initialiser. 变量的声明点(即,名称假定声明赋予它的含义的点,隐藏在更宽范围内具有相同名称的任何其他实体)来自声明者之后,以及任何初始化之前。 So this:
所以这:
int x = x;
^ point of declaration
initialises the local variable x
with its own uninitialised value, giving undefined behaviour (although it's still well-formed, so the compiler shouldn't reject it unless you ask it to). 使用自己的未初始化值初始化局部变量
x
,给出未定义的行为(尽管它仍然是格式良好的,因此编译器不应该拒绝它,除非你要求它)。
While this: 这个:
int x[x];
^ point of declaration
uses the global constant x
within the declarator, which is well-formed and well-defined. 在声明符中使用全局常量
x
,它是格式良好且定义良好的。 It's potentially baffling for human readers, but no problem for the compiler. 这对于人类读者来说可能是令人困惑的,但编译器没有问题。
The rationale for this rule is that it's reasonable to use the address (but not the value) of a variable in its own initialiser, a simple example being 这条规则的基本原理是在自己的初始化器中使用变量的地址(但不是值)是合理的,一个简单的例子是
void * p = &p;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.