【c語言】static修飾變數
阿新 • • 發佈:2018-12-10
static
1.修飾區域性變數
改變了 生命週期,作用域不發生改變 eg:
void test()
{
int i = 0;
i++;
printf("%d\n", i);
}
int main()
{
int i = 0;
for (i = 0; i < 10; i++)
{
test();
}
system("pause");
return 0;
}
程式執行結果為10個1,加上static後
void test() { static int i = 0; i++; printf("%d\n", i); } int main() { int i = 0; for (i = 0; i < 10; i++) { test(); } system("pause"); return 0; }
執行結果為:1 2 3 4 5 6 7 8 9 10 分析: static建立i,i不會被銷燬,生命週期變長但是作用域並沒有改變。 區域性變數存在棧區,棧區資料自動建立,自動銷燬,static變數存在靜態區,(靜態區的資料建立了但不銷燬),所以static是先改變了變數的儲存位置,從而改變了它的生命週期。
2.修飾全域性變數
改變了連結屬性(外->內)
3.修飾函式
改變了連結屬性(外->內)