Namespaces
Variants

Static storage duration

From cppreference.net

一个对象,其标识符在声明时未使用存储类说明符 _Thread_local ,且具有外部或内部 链接 ,或使用了存储类说明符 static ,则具有静态存储期。其生存期贯穿整个程序执行过程,且存储值仅在程序启动前初始化一次。

注释

由于其存储值仅初始化一次,具有静态存储期的对象可以对函数的调用进行性能分析。

关键字 static 的另一种用法是 文件作用域

示例

#include <stdio.h>
void f (void)
{
    static int count = 0;   // 静态变量
    int i = 0;              // 自动变量
    printf("%d %d\n", i++, count++);
}
int main(void)
{
    for (int ndx=0; ndx<10; ++ndx)
        f();
}

输出:

0 0
0 1
0 2
0 3
0 4
0 5
0 6
0 7
0 8
0 9