C库之<cassert>
assert.h定义了一个作为标准调试工具的宏
宏函数
函数
说明
assert
Evaluate assertion (macro)
assert
当使用assert()里,给它一个参数,即一个表示断言为真的表达式。预处理器产生测试该断言的代码。如果断言不为真,则发出一个错误信息告诉断言是什么以及的失败之后,程序会终止。下面是一个例子:
1#include <cstdio> 2#ifndef NDEBUG 3#include <cassert> 4#endif // NDEBUG 5 6void cout_number(int * num) 7{ 8#ifndef NDEBUG 9 assert(num != NULL); 10#endif // NDEBUG 11 printf("%d\n", *num); 12} 13 14int main(int argc, const char **argv) 15{ 16 int a = 100; 17 int *b = NULL; 18 int *c = NULL; 19 20 b = &a; 21 22 cout_number(b); 23 cout_number(c); // Fails 24 25 return 0; 26}
当产生断言时会出现下面这种格式:
Assertion failed: expression, file filename, line line number
这个宏是用来铺获编程错误,而不是用户或运行时错误,因此它通常是禁用程序退出后的调试阶段。