打印错误的值

时间:2014-10-24 02:01:00

标签: c++

下面是我们想要打印x的值的程序,然后它仍然是200,但它应该出来100.我做错了什么?

#include<iostream>

using namespace std;

int x = 50;                //global x

int main ()
{
int x = 100;          //x redeclared local to main

{
    int inn = x;
    x = 200;         //x declared again in inner block

    cout << " This is inner block " << endl;
    cout << " inn = " << inn << endl;
    cout << " x = " << x << endl;
    cout << " ::x = " << :: x << endl;
}   

cout << endl << " This is outer block " << endl;
//value of x should be 100 ,but it is giving 200
cout << " x = " << x << endl;   
cout << " ::x = " << :: x << endl;
return 0;
}    

1 个答案:

答案 0 :(得分:6)

x = 200;         //x declared again in inner block

不,那不是声明x。如果你写了:

int x = 200;

那本来是一个声明,并给你你可能期望的结果。虽然可以在程序的任何地方使用::x访问全局范围x,但如果你在最里面的块中实际声明了另一个x,则该块中的代码无法到达main的外部x(至少不是直接):

how to access a specific scope in c++?

但是如上所述,它只是最里面的块中的赋值,它的范围是main中的x。不是声明。