constexpr 說明符 (C23 起)
來自 cppreference.com
用 constexpr
儲存類說明符宣告的標量物件是常量。它必須根據靜態初始化規則完全且顯式地初始化。它仍然具有與其宣告相適應的連結,並且在執行時存在以獲取其地址;它只是不能在執行時以任何方式修改,即編譯器可以在任何其他常量表達式中使用其對物件固定值的瞭解。
此外,用於此類常量初始化器的常量表達式會在編譯時進行檢查。
浮點型別的初始化器必須在轉換時浮點環境中求值。
對於可以用 constexpr
宣告的物件型別有一些限制。即,以下構造不允許為 constexpr
目錄 |
[編輯] 關鍵詞
[編輯] 註釋
[編輯] 示例
執行此程式碼
#include <fenv.h> #include <stdio.h> int main(void) { constexpr float f = 23.0f; constexpr float g = 33.0f; fesetround(FE_TOWARDZERO); constexpr float h = f / g; // is not affected by fesetround() above printf("%f\n", h); }
輸出
0.696969
[編輯] 參考
- C23 標準 (ISO/IEC 9899:2024)
- 待定 待定 (p: 待定)
[編輯] 另請參閱
C++ 文件,關於
constexpr 型別說明符 |