2020年4月12日 星期日

C 語言 - static

static - Introduction

     靜態變數(Static Variable)在電腦編程領域指在程式執行前系統就為之靜態分配(也即在執行時中不再改變分配情況)儲存空間的一類變數。與之相對應的是在執行時只暫時存在的自動變數(即局部變數)與以動態分配方式取得儲存空間的一些物件,其中自動變數的儲存空間在呼叫棧上分配與釋放。

static + 變數

  
    (1) 宣告在 function 內 ( 記憶體模式 )
    這是比較經典的 Case,因為 Static 參數不會隨著 function 結束而消逝,所以可以用來計算 function 被呼叫的次數。
    #include "hello.h"

    int count(){
        static int count = 0;
        ++count;
        return count;
    }
    (2) 宣告在 function 外 ( 連結模式 ) 
    假設 a.h 跟 b.h 都設了 void foo() 這個函式,這樣你在 main.c 同時 include 時就會編譯錯誤。你有可能會說那我把 void foo() 個別放在 a.c 跟 b.c 就行,但編譯依然會錯誤。因為在連結 .o 檔時編譯器依然會發現。這時 static 就可避免此情況,有點類似 private 的概念,只有自己看得到就不會產生 ambiguous 的問題。


參考資料 :
https://zh.wikipedia.org/wiki/
https://medium.com/@alan81920/

Related Posts:

  • C 語言 - malloc、free 與 calloc malloc 跟 free     一般來說要將函式結果回傳是不能用 pointer,因為一旦函式結束 stack 的空間就會被釋出,所以 pointer 會指向的資料是危險的。這時就會先動態地宣告一個位址給 pointer,但這類的記憶體會被存放在 heap 而非 stack,所以開發者必須自行釋放。 pointer.c void showMalloc(int poi… Read More
  • C 語言 - warning: left shift count >= width of type warning: left shift count >= width of type     一般來說,就是 shift 的 bit 大於資料型態的 bit 數。但有時使用 unsigned long 仍然會出錯,因為 unsigned long 會依照系統的不同,有時是 32 bit 有時是 64 bit,所以這時用 unsigned long long 較為安全 ( 保證 64 bit… Read More
  • C 語言 - struct array 初始化 ( Initializing array of structures ) 初始化 struct array struct student { char* name; int grade; int id; }; 1. 依照當初宣告的順序 struct student myStudents[] = { {"Henry", 3, 1}, {"Marry", 3, 2} }; 1. 依照當初宣告的名子 … Read More
  • C 語言 - size_t 及各個常見類型 typedef unsigned int size_t // 通常定義在 stddef.h int8 : -128 ~ 127 int16 : -32768 ~ 32767 int32 : -2147483648 ~ 2147483647 int64 : -9223372036854775808 ~ 9223372036854775807 uint8 : … Read More
  • C 語言 - CLI ( Command Line Interface ) 設計 (1)CLI 命令列介面     在設計 CLI 的程式時,最好的方法是遵從 IEEE Std 1003 ( POSIX ) 對 program 的 command-line options 之規範。所以用 getopt 去做 parse command-line 是最簡單的,有一點要注意的是 GNU 提供的 getopt 支援 " -- ",這個 PO… Read More

0 意見:

張貼留言

Popular Posts