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

时间:2015-09-24 06:41:16

标签: c++ grid coordinates

#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所在。

3 个答案:

答案 0 :(得分:2)

您在此处从外部范围修改x

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

如果您说过int x = 2;,那么您可能会得到(5,6)。但你没有。

答案 1 :(得分:0)

您已在最后一个范围内为x指定值2,因此它(2,6)。

答案 2 :(得分:-2)

不是它如何工作,因为来自外部范围的变量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?