下面是程序,当我们要打印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;
}
最佳答案
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。不是声明。
关于c++ - 打印错误的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26540370/