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

问一个关于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条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)