先看一段小程序
#includeusing namespace std;
void func1() {
static int a = 1;
a++;
cout << "a = " << a << endl;
}
int main(int argc, char* argv[]) {
cout << "main start" << endl;
for (int i = 0; i < 5; i++) {
func1();
}
cout << "main end" << endl;
}
结果是:
main start
a = 2
a = 3
a = 4
a = 5
a = 6
main end
分析:
虽然func1中入口处有static int a = 1; 但static静态变量,生命周期是从变量创建到程序结束。一旦定义了就不会再次初始化了。