const 限定符表明對象初始化後不可修改。定義時必須初始化,支持兩種方式:
// file1.cpp extern const int BUFSIZE = 4096; // 定義處加 extern,賦予外部鏈接 // file2.cpp extern const int BUFSIZE; // 聲明處也需 extern
綁定臨時對象、字面值或不同類型表達式:
聲明 含義 指針可變? 指向值可變? const int *p指向常量的指針 是 否 int *const p常量指針 否(需初始化) 是 const int *const p指向常量的常量指針 否 否 int const *p同 const int*是 否 口訣:
*左邊有const→ 指向值不可變;右邊有const→ 指針本身不可變。constexpr:編譯期常量表達式 (C++11)
constexpr強制編譯器驗證表達式在編譯期可計算:)
const 整型/枚舉變量constexpr 變量