静态断言 (C11 起)
来自 cppreference.cn
目录 |
[编辑] 语法
_Static_assert ( expression , message ) |
(C11 起)(C23 中已弃用) | ||||||||
static_assert ( expression , message ) |
(C23 起) | ||||||||
_Static_assert ( expression ) |
(C23 起)(C23 中已弃用) | ||||||||
static_assert ( expression ) |
(C23 起) | ||||||||
expression | - | 任何整型常量表达式 |
message | - | 任何字符串字面量 |
此关键字也可用作便捷宏 static_assert,在头文件 <assert.h> 中可用。 |
(C23 前) |
实现也可能将 |
(C23 起) |
[编辑] 解释
常量表达式在编译时求值并与零进行比较。如果它比较等于零,则会发生编译时错误,并且编译器必须显示 message 作为错误消息的一部分(除非基本字符集之外的字符不需要显示)(C23 前)应显示 message (如果提供)作为错误消息的一部分(C23 起)。
否则,如果 expression 不等于零,则什么也不会发生;不发出任何代码。
[编辑] 关键字
[编辑] 示例
运行此代码
#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 静态断言 (页码:待定)
- C17 标准 (ISO/IEC 9899:2018)
- 6.7.10 静态断言 (页码:105)
- 7.2 诊断 <assert.h> (页码:135)
- C11 标准 (ISO/IEC 9899:2011)
- 6.7.10 静态断言 (页码:145)
- 7.2 诊断 <assert.h> (页码:186-187)
[编辑] 参见
如果用户指定的条件不为 true,则中止程序。可能在发布版本中禁用 (函数宏) | |
C++ 文档,关于
static_assert declaration |