令人困惑的 C++全球范围问题
我正在参加 C++ 练习测试,我对一组访问范围和声明点相关的问题感到困惑。这两个问题都是相互关联的..我知道答案..我需要的是正确的解释:
main 末尾的局部变量 x 的值是多少
int x = 5;
int main(int argc, char** argv)
{
int x = x;
return 0;
}
ans: Undefined
y 末尾的 y 的值是多少主要的?
const int x = 5;
int main(int argc, char** argv)
{
int x[x];
int y = sizeof(x) / sizeof(int);
return 0;
}
答案:5
I am taking a C++ practice test and I'm confused with a set of access scope and point of declaration related questions. Both the questions are related to each other..I know the answers..what i need is proper explanation :
What is the value of the local variable x at the end of main
int x = 5;
int main(int argc, char** argv)
{
int x = x;
return 0;
}
ans: Undefined
What is the value of y at the end of main?
const int x = 5;
int main(int argc, char** argv)
{
int x[x];
int y = sizeof(x) / sizeof(int);
return 0;
}
answer: 5
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自标准:3.3.1 [basic.scope.pdecl]
该标准甚至有两个例子来阐明这一点:
这两个例子涵盖了您问题中的两种情况。
From the standard: 3.3.1 [basic.scope.pdecl]
The standard even has two examples to clarify this:
These two examples cover the two cases in your question.
它由内部
x
何时存在(其范围的开始)来控制。该标准部分规定(当前标准中的 3.3.1,即将发布的标准中的 3.3.2)(斜体):对于
int x = x;
,它是在=
点创建的,因此当您将x
分配给它时,它就是 正在使用的内部 x。由于之前没有设置过任何内容,因此它是未定义的。对于
int x[x];
,内部x
在;
处存在,因此它使用外部x
> 作为数组大小。It's controlled by when the inner
x
comes into existence (the start of its scope). The standard states (3.3.1 in the current standard, 3.3.2 in the upcoming one) in part (my italics):With
int x = x;
, it's created at the point of the=
so that when you assignx
to it, that's the inner x which is being used. Since that hasn't been set to anything before, it's undefined.With
int x[x];
, the innerx
comes into existence at the;
so it's using the outerx
as the array size.