const 是型別修飾符,用於宣告「唯讀」物件。被 const 修飾的變數在初始化後,其值在程式執行期間不可修改。編譯器會對寫入操作發出錯誤,並可能將該物件置於唯讀記憶體區段(如 .rodata),進一步由硬體保護。
const int MAX_CONN = 1024; // 常數整數
const double PI = 3.1415926535; // 常數浮點數
const char *GREETING = "Hello"; // 指向常數字串的指標
| 宣告 | 含義 | 可修改項 |
|---|---|---|
const int *p / int const *p | 指向 常數整數 的指標 | 指標 p 本身 |
int *const p | 常數指標,指向整數 | 指向的整數值 *p |
const int *const p | 常數指標,指向常數整數 | 無(雙重唯讀) |
「const 靠近誰,誰就被鎖死」。讀宣告時從右向左讀:
int *const p → p is a const pointer to intconst int *p → p is a pointer to const int// 輸入緩衝區:承諾不修改內容
size_t strlen(const char *str);
// 輸出緩衝區:呼叫者提供空間,函數填充
void get_timestamp(char *buf, size_t len);
// 回傳唯讀指標:防止呼叫者修改內部狀態
const Config *get_global_config(void);
struct Point { int x, y; };
const struct Point ORIGIN = {0, 0}; // 整個結構體唯讀
const int PRIMES[] = {2, 3, 5, 7, 11}; // 陣列唯讀
class Cache {
mutable std::mutex mtx_; // 即使在 const 物件上也可修改
mutable std::unordered_map cache_;
public:
Value get(Key k) const { // const 成員函數
std::lock_guard lk(mtx_);
return cache_[k];
}
};
#define 代替 const:const 有型別、作用域、可除錯,#define 只是文字替換。const:若函數不修改指向內容,參數應宣告為 const T*,提升介面契約清晰度。const_cast 或 C 風格轉型移除 const 後寫入,屬於未定義行為(UB),若物件原本在唯讀段將導致崩潰。const 修飾:const int n = 10; int arr[n]; 在 C 標準中不合法(C++ 則允許)。string.h:strlen(const char*), strcmp(const char*, const char*), memcpy(void*, const void*, size_t)stdlib.h:bsearch(const void*, const void*, ...), qsort(void*, size_t, size_t, int(*)(const void*, const void*))善用 const 能讓編譯器幫你攔截大量邏輯錯誤,也是介面設計專業度的重要標誌。建議在所有新程式碼中「預設加 const,必要時再移除」。