靜態的

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 個元素或空指標,則結果是未定義的行為。由於無法強制執行此操作,因此在將該引數的值傳遞給此類函式時必須格外小心。