#include
using namespace std;
void a(int i);
int x=1;
int main()
{
int x=5;
cout<<"local x in outer scope of main is "<<x<<endl;
{
int x=7;
cout<<"local x in inner scope of main is "<<x<<endl;
}
cout<<"local x in outer scope of main is "<<x<<endl;
a(10); //使用了全局变量
return 0;
}
void a(int i)
{
cout<<endl<<"global x is "<<x<<" on entering a";
x*=i;
cout<<endl<<"global x is "<<x<<" on entering a";
}
这段代码中“a(10);”为什么调用的是“x=1"这个全局变量?
void a(int i)
{
cout<<endl<<"global x is "<<x<<" on entering a";
x*=i;
cout<<endl<<"global x is "<<x<<" on entering a";
}
请看函数a的定义,里面
cout<<endl<<"global x is "<<x<<" on entering a";
这句x在函数中是没有申明的,说明x是全局变量,而我们可以看到在main函数之外就定义了全局变量x,并初始化为1了。
因为a函数中访问的就是全局的x啊
a函数内部没有变量i,那么就是使用全局同名变量
a函数中没有定义x,x只能去调最开始的全局变量x
你可以把大括号看做是作用域。
{:代 -表 -开 -始
}:代 -表 -结 -束
大括号里面的变量的作用域就是当前大括号起始和结束位置。
这样方便记忆,也方便查看 望采纳!!!
a函数先在自己的作用域里找X,找到就用,但没找到,就到全局范围内去找X,然后就用了全局变量。