我的C++变量(范围相关)有什么问题?

What's wrong with my C++ variable(scope related)?

本文关键字:什么 问题 C++ 变量 范围 我的      更新时间:2023-10-16
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
    int x = 0, y = 1, k = 5;
{       
    int x = 1;
    x = 10;
    cout << "x is " << x << ", y is " << y << endl;     
}
cout << "x is " << x << " and k is " << k << endl;
cout << endl;
cout << endl;
{
    int x = 5;
    int y = 6;
    {
        int y = 7;
        x = 2;
    }
    cout << "(x, y) is : (" << x << ", " << y << ")" << endl;
}

cin.get();
return 0;
}

输出为:

x = 10, y = 1

x = 0, k = 5

(x, y) = (2,6)

我认为(x,y)应该是(5,6)。因为这是x和y的坐标

您正在从外部作用域修改x:

{
    int y = 7; // local variable
    x = 2;     // variable from outer scope
}

如果你说的是int x = 2;,那么你可以期望得到(5,6)。但是你没有。

你在最后一个作用域中给x赋值2,因此它是(2,6)。

它不是这样工作的,因为外部作用域的变量x是您在内部作用域中更改的,其中没有其他x来隐藏它。考虑一下这个例子,为什么这是必要的:

static const size_t N = 10;
size_t i = 0;
int array[N];
while (i < 10) {
  const int x = i*i;
  array[i] = x;
  ++i;
} // We're out of the block where i was incremented.  Should this be an infinite loop?
// Should array be uninitialized because this is the scope it was in and we updated it in a nested scope?