C 語言中,函數回傳指標時,實作端通常不希望呼叫端修改指標指向的資料。若直接回傳 `int*`,呼叫端可自由寫入 `*ptr = 999`,導致封裝破壞、資料竄改。解決方案:回傳 `const int*`,利用編譯器強制唯讀語意。
#include <stdio.h>
static const int* getConfigValue(); // 宣告:回傳 const int*
int main() {
const int *val = getConfigValue(); // 接收端也需加 const
printf("Value: %d\n", *val); // ✓ 唯讀存取 OK
// *val = 34; // ✗ 編譯錯誤:assignment of read-only location
return 0;
}
const int* getConfigValue() {
static int internal = 100; // static 延長生命週期
return &internal; // 回傳位址,類型自動轉為 const int*
}
若在呼叫端嘗試修改:
const int *val = getConfigValue();
*val = 34; // 錯誤 C3892: 'val' : you cannot assign to a variable that is const
編譯器直接攔截,保護執行期資料完整性。
| 宣告 | 含義 | 允許修改指向資料? | 允許修改指標指向? |
|---|---|---|---|
const int *p | 指向常數的指標 | ✗ | ✓ |
int *const p | 常數指標 | ✓ | ✗ |
const int *const p | 指向常數的常數指標 | ✗ | ✗ |
「回傳 `const` 指標」是 C 語言以編譯期靜態檢查替代執行期防護的經典手法。配合 `static` 確保物件生命週期,能以零成本實現介面層級的資料保護,是 C API 設計的必備技能。