ljhziyou 2015-04-14 05:02 采纳率: 55.6%
浏览 1712
已采纳

问一个关于c++作用域的问题

#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"这个全局变量?

  • 写回答

6条回答

  • zxj88214 2015-04-14 05:40
    关注
     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了。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?