C 函數只能返回單一值 (通過 return 或寄存器)。需返回多值必須借助 **輸出參數** 或 **聚合類型**。
void max_and_plus100(int x, int y, int *max_out, int *plus100_out) {
int m = (x > y) ? x : y;
*max_out = m;
*plus100_out = m + 100;
}
int main() {
int a, b, max, p100;
scanf("%d %d", &a, &b);
max_and_plus100(a, b, &max, &p100);
printf("Max=%d, Max+100=%d\n", max, p100);
return 0;
}
& 取址,語義上「輸入/輸出」參數混雜,需命名規範 (如 _out 後綴)。
typedef struct {
int max;
int plus100;
} MaxResult;
MaxResult compute_max(int x, int y) {
MaxResult r;
r.max = (x > y) ? x : y;
r.plus100 = r.max + 100;
return r; // 結構體值返回 (C99 保證支援)
}
int main() {
MaxResult res = compute_max(123, 45);
printf("Max=%d, Max+100=%d\n", res.max, res.plus100);
return 0;
}
static int g_max, g_plus100; // 檔案內部可見
void compute(int x, int y) {
g_max = (x > y) ? x : y;
g_plus100 = g_max + 100;
}
// 僅用於極簡單/單執行緒/教學示例
// 返回指標,調用者負責 free
int *find_all_max(const int *arr, size_t n, size_t *count_out) {
// ... 找出所有最大值位置 ...
int *res = malloc(*count_out * sizeof(int));
// ... 填充 ...
return res;
}
| 場景 | 推薦模式 | 理由 |
|---|---|---|
| 2~3 個基本類型輸出 | 指標參數 | 零開銷、通用、C89 相容 |
| 返回邏輯相關的多字段聚合 | 結構體返回 | 語意自文檔化、類型安全 |
| 不定數量結果 | 輸出參數 + 動態分配 | 靈活控制生命週期 |
| 執行緒局部/上下文狀態 | Thread-local storage (C11 _Thread_local) | 避免全域變量競爭 |
// 原錯誤:連續兩個 return,第二個永不執行
int max(int x,int y,int z,int h) {
z = x>y? x:y;
return z; // 函數在此結束
h = z+100; // 死代碼
return h;
}
// 正確:指標參數版
void max_correct(int x, int y, int *max_out, int *plus100_out) {
int m = (x > y) ? x : y;
*max_out = m;
*plus100_out = m + 100;
}