函數 A 調用函數 B,要求 B 每次調用返回不同數值。
在 B 函數內部使用 static 局部變量保存狀態:
int B() {
static int counter = 0;
return ++counter; // 每次調用返回 1,2,3...
}
// 或根據業務邏輯
int B() {
static int values[] = {10, 20, 30};
static int idx = 0;
return values[idx++ % 3];
}
static 變量在程序生命周期內僅初始化一次,保持值不隨函數返回銷毀。這是實現「有狀態函數」的最簡單標準方法。