int add(int a) {
int b = 0;
b += 1; // 每次調用 b 都是局部變量,初始化為 0
return b; // 僅返回 1
}
int main() {
for (int i = 0; i <= 5; i++) {
printf("%d\n", add(0)); // 輸出六個 1
}
}
C 語言參數傳遞是「值傳遞」。函數內部的參數與局部變量在棧幀中,函數返回後棧幀銷毀,**狀態不會保留到下一次調用**。
| 模式 | 代碼關鍵點 | 適用場景 |
|---|---|---|
| 靜態局部變量 | static int b = 0; b += 1; return b; | 單函數內保持狀態,全局唯一 |
| 指針/引用參數 | void add(int *b) { *b += 1; } 主程序傳 &counter | 調用方控制生命週期,多實例互不干擾 |
| 全局/文件靜態變量 | static int g_counter = 0; int add() { return ++g_counter; } | 模塊級共享狀態,需注意線程安全 |
#include
void add(int *counter) {
*counter = *counter + 1;
}
int main() {
int cnt = 0;
for (int i = 0; i <= 5; i++) {
add(&cnt);
printf("%d\n", cnt); // 輸出 1 2 3 4 5 6
}
return 0;
}
void add(int &counter) { ++counter; }
int b = 0 每次調用都重置,**無法跨調用保持狀態**。