标准里说对于 function 里面 static 变量只说了两点:
- 分配在静态存储区
- 第一次遇到的时候进行初始化,之后每次跳过。
Variables declared at block scope with the specifier static have static storage duration but are initialized the first time control passes through their declaration (unless their initialization is zero- or constant-initialization, which can be performed before the block is first entered). On all further calls, the declaration is skipped.
https://en.cppreference.com/w/cpp/language/storage_duration
比如
int f()
{
static int a = 0;
}
int main()
{
f();
std::cout << "---------------" << std::endl;
f();
return 0;
}
- 程序起来,静态存储区创建 int a; 此时并未运行到 f(),这时静态存储区的值 a 是否 undefined?还是说类似全局变量初始化,数值类型给 0 值,字符串给空?
- 第一次进入 f()运行到 static int a = 0 时,静态存储区的 a 被初始化为 0 ?之后每次进入 f()这个语句直接被忽略掉?编译器是如何实现的?类似于一个 loop ?初始值 cnt=1,用完 cnt--,下次 check 值是否为 0 进行跳转?