C++之局部static变量

来源:互联网 发布:淘宝自动刷单软件 编辑:程序博客网 时间:2024/06/04 17:51

static其他特性不多说,就说一点,当变量为局部static变量时,如果不知道它的特性你会欲哭无泪。今天在debug项目时就发现了这个坑。直接看两个例子吧。

#include<iostream>using namespace std;int cnt=1;void f(){static int test = cnt;cout<<test<<endl;cnt++;}int main(){f();f();f();cout<<cnt<<endl;return 0;}

输出结果可能会让你大吃一惊:

1

1

1

4

再看另一段程序

#include<iostream>using namespace std;int cnt=1;void f(){static int test;test = cnt;cout<<test<<endl;cnt++;}int main(){f();f();f();cout<<cnt<<endl;return 0;}
输出:

1

2

3

4

两段不同程序差别在哪呢?局部static变量test在函数f()内定义。但是C++规定,局部static变量只会初始化一次!所以第一个程序中后面调用两次f()都不会初始化test。而第二个程序并不是初始化,而是赋值! static int test =cnt与 static int test; test = cnt是不等价的!!

1 0
原创粉丝点击