静态的

static 存储类用于不同的目的,具体取决于文件中声明的位置:

  1. 仅将标识符限制在该转换单元 (scope = file)。

    /* No other translation unit can use this variable. */
    static int i;
    
    /* Same; static is attached to the function type of f, not the return type int. */
    static int f(int n);
    
  2. 要保存数据以便在下次调用函数时使用(scope = block):

     void foo()
     {
         static int a = 0; /* has static storage duration and its lifetime is the
                            * entire execution of the program; initialized to 0 on 
                            * first function call */ 
         int b = 0; /* b has block scope and has automatic storage duration and 
                     * only "exists" within function */
    
         a += 10;
         b += 10; 
    
         printf("static int a = %d, int b = %d\n", a, b);
     }
    
     int main(void)
     {
         int i;
         for (i = 0; i < 5; i++)
         {
             foo();
         }
    
         return 0;
     }
    

    此代码打印:

     static int a = 10, int b = 10
     static int a = 20, int b = 10
     static int a = 30, int b = 10
     static int a = 40, int b = 10
     static int a = 50, int b = 10
    

即使从多个不同的线程调用,静态变量也会保留其值。

Version >= C99

  1. 在函数参数中用于表示数组应具有恒定的最小元素数和非 null 参数:

    /* a is expected to have at least 512 elements. */
    void printInts(int a[static 512])
    {
        size_t i;
        for (i = 0; i < 512; ++i)
            printf("%d\n", a[i]);
    }
    

    所需的项目数(甚至非空指针)不一定由编译器检查,如果没有足够的元素,编译器不需要以任何方式通知你。如果程序员传递少于 512 个元素或空指针,则结果是未定义的行为。由于无法强制执行此操作,因此在将该参数的值传递给此类函数时必须格外小心。