static为静态变量,其数据存储在静态存储区,也叫全局数据区。很多文章上都把他分为“面向过程的static”和“面向函数的static”来进行讲解。我们这里仅仅从“面向过程的static”也就是静态全局变量和静态局部变量方面来进行阐述。
1、 未被初始化的静态变量自动初始化为0
int main() { static int num; cout<<num<<endl; return 0; }
2、静态存储区的数据不会因为函数退出而释放空间
1 #include<iostream> 2 3 using namespace std; 4 5 static int sta_num = 9; 6 void plu(int); 7 8 int main() 9 { 10 int int_num = 9; 11 12 plu(int_num); 13 14 cout<<"sta_num = "<<sta_num<<endl; 15 cout<<"int_num = "<<int_num<<endl; 16 17 return 0; 18 } 19 20 void plu(int y) 21 { 22 for(int num = 0;num<3;num++) 23 { 24 sta_num += 1; 25 y += 1; 26 } 27 }
1 int f() 2 { 3 static int num; 4 cout<<num<<endl; 5 num++; 6 return 0; 7 } 8 int main() 9 { 10 f(); 11 f(); 12 return 0; 13 }
上边第二个例子的输出结果为0 1。从以上两个例子中我们可以看出:静态变量不会因为函数的的退出而释放空间,而且第二个例子中我们还能得到一个信息,在定义静态变量之后只初始化一次,以后的再次调用不会再重新初始化,而是用上次运行后的结果。
3、因为静态变量的值存储在静态存储区,而函数的参数存储在堆中,所以静态变量不能作为形参进行传递。
void f(static int , int);//错误的
对于静态全局变量来说,本身就是全局性的,本身就不需要传递。
对于静态局部变量,在函数中用时,还涉及到作用域的问题,也就是接下来要说的第四点。
4、静态局部变量作用域
静态局部变量除具备上边特性外,还有一个与静态全局变量的不同点,那就是作用域。全局变量作用于全局,局部变量作用于局部,静态变量也是如此。所以静态局部变量的特点就是,数据存储在静态存储区,而作用在所定义的局部。
下边是一个错误代码
1 void test(); 2 void new_test(int); 3 int main() 4 { 5 test(); 6 new_test(); 7 return 0; 8 } 9 10 void test() 11 { 12 static int sta_num = 9; 13 } 14 void new_test(int b) 15 { 16 b = sta_num; 17 cout<<"b = "<<b<<endl; 18 } 19 //test.cpp: 在函数‘void new_test(int)’中: 20 //test.cpp: ‘sta_num’在此作用域中尚未声明
原文:http://www.cnblogs.com/kbe317/p/3859382.html