assert
来自cppreference.com
                    
                                        
                    
                    
                                                            
                    | 在标头  <assert.h>定义 | ||
| #ifdef NDEBUG #define assert(condition) ((void)0) | ||
宏 assert 的定义依赖于标准库不定义的另一个宏 NDEBUG 。
若 NDEBUG 在包含了 <assert.h> 的源代码中的点定义为宏名,则 assert 不做任何事。
若不定义 NDEBUG ,则 assert 将其参数(必须拥有标量类型)与零比较相等。若相等,则 assert 在标准错误输出上输出实现指定的诊断信息,并调用 abort() 。诊断信息要求包含表达式的文本,还有预定义变量 __func__ 与 (C99 起)预定义宏 __FILE__、 __LINE__ 的值。
参数
| condition | - | 标量类型表达式 | 
返回值
(无)
注解
没有标准化的添加消息到 assert 错误的接口。一个包含它的方式是使用逗号运算符:
assert(("There are five lights", 2 + 2 == 5));
assert 在 Microsoft CRT 中的实现不遵从 C99 以及后续标准版本,因为其底层函数 ( _wassert )不接收 __func__ 或等价的替代品。
示例
运行此代码
输出:
output with NDEBUG not defined: a.out: main.cpp:10: main: Assertion `x >= 0.0' failed. output with NDEBUG defined: sqrt(x) = -nan
引用
- C17 标准(ISO/IEC 9899:2018):
- 7.2.1.1 The assert macro (第 135 页)
 
- C11 标准(ISO/IEC 9899:2011):
- 7.2.1.1 The assert macro (第 186-187 页)
 
- C99 标准(ISO/IEC 9899:1999):
- 7.2.1.1 The assert macro (第 169 页)
 
- C89/C90 标准(ISO/IEC 9899:1990):
- 4.2.1.1 The assert macro
 
参阅
| 引发非正常的程序终止(不清理) (函数) |