令人困惑的 C++全球范围问题

发布于 2024-10-05 23:56:09 字数 444 浏览 4 评论 0原文

我正在参加 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蓝眸 2024-10-12 23:56:09

来自标准:3.3.1 [basic.scope.pdecl]

名称的声明点紧接在其完整声明符(第 8 条)之后和其初始化程序(如果有)之前,除非下面另有说明。 p>

该标准甚至有两个例子来阐明这一点:

int x = 12;
{ int x = x; }

此处,第二个 x 使用其自己的(不确定)值进行初始化。

[注意:非本地名称在隐藏它的本地名称声明之前一直保持可见。 [示例:

const int i = 2;
{ int i[i]; }

声明一个包含两个整数的局部数组。 ]]

这两个例子涵盖了您问题中的两种情况。

From the standard: 3.3.1 [basic.scope.pdecl]

The point of declaration for a name is immediately after its complete declarator (clause 8) and before its initializer (if any), except as noted below.

The standard even has two examples to clarify this:

int x = 12;
{ int x = x; }

Here the second x is initialized with its own (indeterminate) value.

[Note: a nonlocal name remains visible up to the point of declaration of the local name that hides it. [Example:

const int i = 2;
{ int i[i]; }

declares a local array of two integers. ]]

These two examples cover the two cases in your question.

×纯※雪 2024-10-12 23:56:09

它由内部 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):

The point of declaration for a name is immediately after its complete declarator and before its initializer.

With int x = x;, it's created at the point of the = so that when you assign x 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 inner x comes into existence at the ; so it's using the outer x as the array size.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文