[轉]C語言的static用法
1. 使用在全域變數或全域函式 (Global variable & Global function)
讓該變數(或該函式)的可視範圍只侷限在該檔案內,其他的 .c檔看不到此變數(或函式)的存在。
既使其他檔案用extern宣告也看不到!套句行話來說,他把Global的變數或函數變成了「internal linkage」,當Linker在找symbol時是會忽略它的。
(在C++中也相容這種用法,不過被視為比較不建議的舊的用法,C++比較建議使用unnamed namespace。)
使用時機:當此全域變數(或全域函式)不想被其他檔案引用和修改時,或者不同檔案可以使用相同名字的全域變數(或全域函式)而不會產生命名衝突。
2. 使用在函式內的區域變數 (Local variable)
因為區域變數預設就是動態變數,而在區域變數前加上static修飾字則會將變數由動態(dynamic)變數轉為靜態(static)變數,靜態變數的壽命(lifetime)與動態變數不同,靜態變數會一直存在,直到程式結束為止。
使用時機:這種很適合用來做統計次數的功能(某函式被呼叫幾次),例如以下的代碼...
#include<stdio.h> int ff(){ int ans = 0; return ans++; } int gg(){ static int ans = 0; return ans++; } int main(){ printf("ff: %d %d %d\n", ff(),ff(),ff()); printf("ff: %d %d %d\n", gg(),gg(),gg()); }
output:
ff: 0 0 0
ff: 2 1 0
-------
A const
is a promise that you will not try to modify the value once set.
A static
variable means that the object's lifetime is the entire execution of the program and it's value is initialized only once before the program startup. All statics are initialized if you do not explicitly set a value to them.The manner and timing of static initialization is unspecified.
C99 borrowed the use of const
from C++. On the other hand, static
has been the source of many debates (in both languages) because of its often confusing semantics.
Also, with C++0x, the use of the static keyword is deprecated when declaring objects in namespace scope will be deprecated.
The longer answer: More on the keywords than you wanted to know (right from the standards)