[英]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;
}
The output is:输出是:
x is 10, y is 1 x 是 10,y 是 1
x is 0 and k is 5 x 为 0,k 为 5
(x, y) is : (2, 6) (x, y) 是 : (2, 6)
I think (x,y) should be (5,6).我认为 (x,y) 应该是 (5,6)。 Because that's the coordinates x and y are in.因为这是 x 和 y 所在的坐标。
You're modifying x
from the outer scope here:您正在此处从外部范围修改x
:
{
int y = 7; // local variable
x = 2; // variable from outer scope
}
If you had said int x = 2;
如果你说int x = 2;
then you could expect to get (5,6)
.那么你可以期望得到(5,6)
。 But you didn't.但你没有。
您已在最后一个范围内为 x 分配了值 2,因此它是 (2,6)。
Not how it works, because the variable x
from the outer scope was the one you changed in the inner scope, where there is no other x to hide it.不是它是如何工作的,因为外部作用域中的变量x
是您在内部作用域中更改的变量,其中没有其他 x 可以隐藏它。 Consider this example of why this is necessary:考虑为什么这是必要的这个例子:
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?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.