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

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

#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)。但你没有。

您在最后一个范围内将值 2 赋给了 x,因此它是 (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?