assert_C语言中文网
| 定义于头文件 |
||
| #ifdef NDEBUG #define assert(condition) ((void)0) |
||
宏 assert 的定义依赖于标准库不定义的另一个宏 NDEBUG 。
若 NDEBUG 在包含了 <assert.h> 的源代码中的点定义为宏名,则 assert 不做任何事。
若不定义 NDEBUG ,则 assert 将其参数(必须拥有标量类型)与零比较相等。若相等,则 assert 在标准错误输出上输出实现指定的诊断信息,并调用 abort 。诊断信息要求包含表达式的文本,还有标准宏 __FILE__ 、 __LINE__ 以及预定义变量 __func__ (C99 起)的值。
参数
返回值
(无)
示例
#include <stdio.h> // 反注释可禁用 assert() // #define NDEBUG #include <assert.h> #include <math.h> int main(void) { double x = -1.0; assert(x >= 0.0); printf("sqrt(x) = %f\n", sqrt(x)); return 0; }
输出:
output with NDEBUG not defined: a.out: main.cpp:10: main: Assertion `x >= 0.0' failed. output with NDEBUG defined: sqrt(x) = -nan
引用
- C11 standard (ISO/IEC 9899:2011):
- 7.2.1.1 The assert macro (p: 186-187)
- C99 standard (ISO/IEC 9899:1999):
- 7.2.1.1 The assert macro (p: 169)
- C89/C90 standard (ISO/IEC 9899:1990):
- 4.2.1.1 The assert macro
参阅
| 引发非正常的程序终止(不清理) (函数) |