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

来源:互联网 发布:福尔摩斯探案集 知乎 编辑:程序博客网 时间:2024/05/17 03:00

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

[cpp] view plaincopy
  1. #include <iostream>  
[cpp] view plaincopy
  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

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


原创粉丝点击