gpt4 book ai didi

c++ - 我想确认我对变量作用域的理解在 C++ 中是正确的

转载 作者:太空狗 更新时间:2023-10-29 20:20:30 25 4
gpt4 key购买 nike

我已经阅读了关于作用域的内容,并且认为我到目前为止已经理解了它。我遇到了另一个程序的问题,在尝试修复它时,我发现循环范围内的变量的行为与我预期的非常不一样。所以我制作了这个程序来展示我的意思:

#include <iostream>

using namespace std;

int main()
{
int num = 6;
for (int i = 0; i < 5; i++)
{
cout << num;
int num = 5;
cout << num;
}
}

我预计 for 循环的第一次运行时,第一个 cout << num 将是未定义的,因为它是一个新范围并且 num 尚未定义。但相反,它只是使用了前一个作用域中的 num 值。然后当 num 在循环内初始化为 5 时,之后,num 的所有输出都应该是 5。但是输出是 656565...

因此,使用这些信息,我制作了一个我认为变量作用域的模型,它看起来像这样:

Scope Diagram

所以在图像中你可以看到我认为作用域是如何工作的,我认为对于循环中的每次迭代,循环都会获得一个新的变量作用域,然后在循环结束时删除它的作用域并得到一个新的一个在下一次迭代的开始,它解释了为什么 for 循环使用前一个作用域中的 num 直到 num 在当前作用域中被重新初始化。我的理解正确吗?

最佳答案

Is my understanding correct?

是的,但是 num 重新初始化。它定义了另一个变量。
“内部” num shadows “外部”num

因为两个 num 都有 block 作用域,根据basic.scope.block :

A name declared in a block is local to that block; it has block scope. Its potential scope begins at its point of declaration and ends at the end of its block. A variable declared at block scope is a local variable.

int main() {
int num = 6; // block scope (a) ---- point of declaration for (a) begins
for (int i = 0; i < 5; i++)
{
cout << num; // uses (a)
int num = 5; // block scope (b) ---- point of declaration for (b) begins
cout << num; // uses (b) ||
} // ---- (b) goes out of scope here
} // ---- (a) goes out of scope here

关于c++ - 我想确认我对变量作用域的理解在 C++ 中是正确的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50887886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com