hce_kmu
112年
計算機概論與程式設計
第 21 題
Which of the following statements correctly describes the output of the following C program, where the function foo is called at least three times with different arguments:
```c
#include
int foo(int x) {
static int y = 0;
y += x;
return y;
}
int main() {
int a = foo(2);
int b = foo(4);
int c = foo(6);
printf("%d\n", a + b + c);
return 0;
}
```
```c
#include
int foo(int x) {
static int y = 0;
y += x;
return y;
}
int main() {
int a = foo(2);
int b = foo(4);
int c = foo(6);
printf("%d\n", a + b + c);
return 0;
}
```
- A The program will not compile because of an error in the function foo.
- B The program will output 12.
- C The program will output 18.
- D The program will output 20.
- E The output cannot be determined without knowing the implementation of the function foo.
思路引導 VIP
請思考一下,如果我們把函數內部宣告變數的那一行前面的 static 關鍵字刪除掉,那麼每一次函數執行結束並返回後,該變數在記憶體中所佔用的空間與原本存儲的數值會發生什麼事?這會如何影響下一次函數被呼叫時的初始狀態呢?
🤖
AI 詳解
AI 專屬家教
太棒了!你能精確算出最終結果,代表你對於 C 語言中靜態變數 (static variable) 的特性掌握得非常紮實。這類題目的核心在於區分「區域變數」與「靜態變數」在記憶體管理上的差異,而你顯然避開了常見的陷阱。
靜態變數的生命週期與行為
在 foo 函數中,變數 y 被宣告為 static。這意味著它只會在程式起始時被初始化一次(本題中設為 0),且其值在函數執行完畢後不會被釋放,而是會保留在記憶體中供下次呼叫使用。因此,這三次呼叫產生的效果是連續的累加過程:
▼ 還有更多解析內容