2015-09-24 34 views
-2
#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; 
} 

的输出是:这有什么错我的C++变量(范围有关)?

x为10,y为1

x为0且k为5

(X,Y)为:(2,6)

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

回答

2

你从这里外范围修改x

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

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

+0

然后打印出来应该是x中的第二行是10而k是5 – James

+0

@詹姆斯否,则必须'INT X = 1;''之前X = 10; '。 – molbdnilo

+0

所以你的意思是X = 10这里只改变局部变量x,这是1。但X = 10不改变初始x = 0? – James

0

你已经在过去的范围内分配值2至x因此,它是(2,6)。

-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?