所有未加static首碼的全域變數和函數都具有全域可見度。為理解這句話,我舉例來說明
static的第三個作用是預設初始化為0。其實全域變數也具備這一屬性,因為全域變數也儲存在待用資料區。在待用資料區,記憶體中所有的位元組預設值都是0x00,某些時候這一特點可以減少程式員的工作量
#include <stdio.h>
int g = 10;
main(){
int i =0;
void f1();
f1();
printf(" after first call n");
f1();
printf("after second call n");
f1();
printf("after third call n");
}
void f1()
{
static int k=0;
int j = 10;
printf("value of k %d j %d",k,j);
k=k+10;
}
利用static實現全域變數賦值方法
儲存在待用資料區的變數會在程式剛開始運行時就完成初始化,也是唯一的一次初始化。共有兩種變數儲存在靜態儲存區:全域變數和static變數,只不過和全域變數比起來,static可以控制變數的可見範圍,說到底static還是用來隱藏的
#include <stdio.h>
void test1(void){
int count = 0;
printf("ntest1 count = %d ", ++count );
}
void test2(void){
static int count = 0;
printf("ntest2 count = %d ", ++count );
}
int main(void)
{
int i;
for(i = 0; i < 5; i++ )
{
test1();
test2();
}
return 0;
}
輸出值為
test1 count = 1
test2 count = 1
test1 count = 1
test2 count = 2
test1 count = 1
test2 count = 3
test1 count = 1
test2 count = 4
test1 count = 1
test2 count = 5