如果
staticVar
是定义在函数外的全局静态变量,那么它的作用域仅限于当前文件(内部链接),同样在整个程序生命周期内只会被初始化一次。
示例 1:静态局部变量
#include <iostream>
void func() {
static int staticVar = 666;
std::cout << "staticVar = " << staticVar << std::endl;
staticVar++;
}
int main() {
func();
func();
func();
return 0;
}
输出:
staticVar = 666
staticVar = 667
staticVar = 668
示例 2:静态全局变量
#include <iostream>
static int staticVar = 666;
void func() {
std::cout << "staticVar = " << staticVar << std::endl;
staticVar++;
}
int main() {
func();
func();
return 0;
}
输出:
staticVar = 666
staticVar = 667
特点
-