錯誤代碼
int max(int a, int b) {
if (a > b) return a;
// 缺少 else return b; 或 末尾 return b;
}
後果
- 若
a <= b,**控制流到達函數末尾無返回** → **未定義行為 (UB)**。
- 表現為:返回隨機垃圾值、程序崩潰、看似正常但極不穩定。
- 現代編譯器
-Wreturn-type (GCC/Clang) / /W4 (MSVC) 會**警告**:「control reaches end of non-void function」。
修正版本
// 版本 1:雙返回
int max(int a, int b) {
if (a > b) return a;
else return b;
}
// 版本 2:單返回 (推薦,便於調試設置斷點)
int max(int a, int b) {
int result = (a > b) ? a : b;
return result;
}
// 版本 3:斷言防禦 (針對不可達路徑)
int max(int a, int b) {
if (a > b) return a;
if (a <= b) return b;
// 理論不可達
__builtin_unreachable(); // GCC/Clang 提示優化
}
最佳實踐
- **所有非 void 函數必須在所有路徑返回值**。
- **開啟編譯器警告並視為錯誤** (
-Werror=return-type)。
- **單一出口點** 風格 (最後統一
return ret;) 便於調試與資源清理。
- **靜態分析工具** (Cppcheck, Clang Static Analyzer, Coverity) 可自動檢測缺失返回。