分享一道笔试题目--关于static和extern变量的问题

转自:http://blog.csdn.net/liuzhanchen1987/article/details/8119235

[cpp]  view plain copy
  1. #include <iostream>  
[cpp]  view plain copy
  1. using namespace std;  
  2.   
  3. int count = 3;  
  4. int main()  
  5. {  
  6.     int i, sum, count = 2;  
  7.     //输出main函数的count即为2  
  8.     //cout<<count<<endl;  
  9.     for(i = 0, sum = 0; i < count; i += 2,count++)  
  10.     {  
  11.         //输出main函数的count即为每次循环加1  
  12.         //cout<<count<<endl;  
  13.         //该语句只执行一次,即只开辟一次内存空间所以每次循环  
  14.         //改变count都不会被重置为4  
  15.         static int count = 4;  
  16.         //static中的count  
  17.         //cout<<count<<endl;  
  18.         //static中的count  
  19.         count++;  
  20.         //static中的count  
  21.         //cout<<count<<endl;  
  22.         if(i % 2 == 0)  
  23.         {  
  24.             //全局的count,即为main函数上面的count  
  25.             extern int count;  
  26.             //全局的count,即为main函数上面的count  
  27.             count++;  
  28.             //全局的count,即为main函数上面的count  
  29.             //cout<<count<<endl;  
  30.             //全局的count,即为main函数上面的count  
  31.             sum += count;  
  32.         }  
  33.         //static中的count  
  34.         //cout<<count<<endl;  
  35.         //static中的count  
  36.         sum += count;  
  37.     }  
  38.     //main函数中的count  
  39.     cout<<count<<' '<<sum<<endl;  
  40.     return 0;  
  41. }  

运行结果是4 20

具体的原因见代码注释,也可将注释掉的输出代码释放,查看运行的结果。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值