1.static无论是体现累加还是覆盖初始值功能,都必须在一次程序运行中进行,才能展示它的功能,如果分为两次运行,就会被初始化两次,没任何意义,就和普通变量一样了,上次改变的值不会被这次使用(因为是两次运行)。
# include<iostream>
# include<string>
using namespace std;
int test() {
//初始化只有一次,后面直接绕过,
static int c = 1;
//累加工作必须是一次运行
c = c + 1;
return c;
}
int main() {
int flag = 0;
//累加的触发器
for (int i = 0; i < 3; i++) {
cout << test() << endl;
}
}
运行结果为:
2
3
4