Ch.5曾討論過儲存類別指定詞static。 static區域變數在程式執行期間會㇐直存在,但只有在此函式本體內才能夠「看得到」它。 可以將static用於㇐個區域陣列的定義上,這樣陣列就不會在每次函式呼叫時產生以及指定初始值,而且陣列也不會在每次函式離開這個程式時加以清除。 這樣可以減少程式的執行時間,特別是經常呼叫含有大型陣列函式的程式效果顯著。
增進效能的小技巧:如果函式當中含有自動陣列,其函式出入該區段非常頻繁,則應該將此陣列指定為static,才不用在每次呼叫函式時都建立該陣列。
宣告成 static 的陣列會自動在程式開始進行初始化,若沒有明確地為static陣列設定初值,預設就會將陣列元素的初始值設定為零。
圖6.11的程式含有宣告 static 區域陣列(#24)的staticArrayInit 函式(#21-39),以及含有自動區域陣列(#45)的automaticArrayInit 函式(#42-60)。



// Fig. 6.11: fig06_11.c
// Static arrays are initialized to zero if not explicitly initialized.
#include <stdio.h>
void staticArrayInit(void); // function prototype
void automaticArrayInit(void); // function prototype
// function main begins program execution
int main(void){
puts("First call to each function:");
staticArrayInit();
automaticArrayInit();
puts("\\n\\nSecond call to each function: ");
staticArrayInit();
automaticArrayInit();
}
// function to demonstrate a static local array
void staticArrayInit(void){
// initializes elements to 0 before the function is called
static int array1[3];
puts("\\nValues on entering staticArrayInit:");
// output contents of arrayl
for (size_t i = 0; i <= 2; ++i) {
printf("array1[%u]= %d ", i, array1[i]);
}
puts("\\nValues on exiting staticArrayInit:");
// modify and output contents of arrayl
for (size_t i = 0; i <= 2; ++i) {
printf("array1[%u]= %d ", i, array1[i] += 5);
}
}
// function to demonstrate an automatic local array
void automaticArrayInit(void){
// initializes elements each time function is called
int array2[3] = {1, 2, 3};
puts("\\n\\nValues on entering automaticArrayInit:");
// output contents of array?
for (size_t i = 0; i <= 2; ++i) {
printf("array2 [%u]= %d ", i, array2[i]);
}
puts("\\nValues on exiting automaticArrayInit:");
// modify and output contents of array2
for (size_t i = 0; i <= 2; ++i) {
printf("array2[%u] = %d ", i, array2[i] += 5);
}
}

