c++之变量的生存期及可见性

 1 #include <iostream>
 2 using namespace std;
 3 
 4 //变量的生存期及可见性
 5 int i = 1;    // i全局变量具有静态生存期
 6 void other(){
 7     static int a = 2;
 8     static int b;        //变量a和b为静态局部变量,具有全局寿命,但是只有在本函数中可见,
 9                         //并且只有当函数第一次被调用时,a和b才会被创建,意思就是说上面两
10                         //句话,只可能被执行一次,当你下一次调用这个函数时a和b的值还是上一次
11                         //的最终值。
12     int c = 10;        //c为局部变量,具有动态生存期,每次调用函数时都会进行初始化。
13     a += 2;    c +=2;    i += 2;
14     cout << "--->other---" << endl;
15     cout << "a:" << a << "c:" << c << "i:" << i << endl;
16     b = a;
17 }
18 
19 void main(){
20     static int a;        //a为静态局部变量,具有全局寿命,局部可见,初始化时如果没有赋值,则系统自动赋值为零;
21     int b = -10;
22     int c = 0;                //b和c为局部变量,具有动态生存期,必须赋值才能使用。
23     cout << "--->main---" << endl;
24     cout << "a:" << a << "b:" << b << "c:" << c << "i:" << i << endl;
25     c += 8;
26     other();
27     cout << "--->main---" << endl;
28     cout << "a:" << a << "b:" << b << "c:" << c << "i:" << i << endl;
29     i += 10;
30     other();
31 }

 

posted @ 2015-03-05 22:14  溈鉨wo乄菰単  阅读(388)  评论(0编辑  收藏  举报