靜態斷言 (從 C11 開始)
來自 cppreference.com
目錄 |
[編輯] 語法
_Static_assert ( 表示式 , 訊息 ) |
(C11 起)(C23 已棄用) | ||||||||
static_assert ( 表示式 , 訊息 ) |
(自 C23 起) | ||||||||
_Static_assert ( 表示式 ) |
(從 C23 開始)(在 C23 中已棄用) | ||||||||
static_assert ( 表示式 ) |
(自 C23 起) | ||||||||
表示式 | - | 任何 整型常量表達式 |
訊息 | - | 任何 字串字面量 |
此關鍵字也可作為便利宏 static_assert 使用,該宏在標頭檔案 <assert.h> 中提供。 |
(直至 C23) |
實現還可以將 |
(自 C23 起) |
[編輯] 說明
常量表達式在編譯時求值並與零比較。如果它等於零,則發生編譯時錯誤,並且編譯器必須將訊息作為錯誤訊息的一部分顯示(除了不要求顯示基本字元集中不包含的字元)(直到 C23)應該將訊息(如果提供)作為錯誤訊息的一部分顯示(從 C23 開始)。
否則,如果 表示式 不等於零,則不發生任何事情;不發出任何程式碼。
[編輯] 關鍵詞
[編輯] 示例
執行此程式碼
#include <assert.h> // no longer needed since C23 int main(void) { // Test if math works, C23: static_assert((2 + 2) % 3 == 1, "Whoa dude, you knew!"); // Pre-C23 alternative: _Static_assert(2 + 2 * 2 == 6, "Lucky guess!?"); // This will produce an error at compile time. // static_assert(sizeof(int) < sizeof(char), "Unmet condition!"); constexpr int _42 = 2 * 3 * 2 * 3 + 2 * 3; static_assert(_42 == 42); // the message string can be omitted. // const int _13 = 13; // Compile time error - not an integer constant expression: // static_assert(_13 == 13); }
[編輯] 參考文獻
- C23 標準 (ISO/IEC 9899:2024)
- 6.7.11 靜態斷言 (p: 待定)
- C17 標準 (ISO/IEC 9899:2018)
- 6.7.10 靜態斷言 (p: 105)
- 7.2 診斷 <assert.h> (p: 135)
- C11 標準 (ISO/IEC 9899:2011)
- 6.7.10 靜態斷言 (p: 145)
- 7.2 診斷 <assert.h> (p: 186-187)
[編輯] 另請參閱
如果使用者指定的條件不為 true,則中止程式。可以在釋出版本中停用。 (函式宏) | |
C++ 文件 關於
static_assert 宣告 |