assert用法总结

来源:互联网 发布:java中if else赋值 编辑:程序博客网 时间:2024/06/01 09:47
 

assert宏的原型定义在<assert.h>中,其作用是如果它的条件返回错误,则终止程序执行,原型定义:
#include <assert.h>
void assert( int expression );

assert的作用是现计算表达式 expression ,如果其值为假(即为0),那么它先向stderr打印一条出错信息,
然后通过调用 abort 来终止程序运行。

验证:

ret = 0;

assert(ret != 0);

printf("hello!\n");

结果:因为,ret=0 ,所以断言返回结果出错,所以接下去都不执行printf("hello!\n");

[root@localhost stFtp]# ./stFtpClient
stFtpClient: main.c:7: main: Assertion `ret != 0' failed.
Aborted
[root@localhost stFtp]#

使用assert的缺点是,频繁的调用会极大的影响程序的性能,增加额外的开销。
在调试结束后,可以通过在包含#include <assert.h>的语句之前插入 #define NDEBUG 来禁用assert调用,示例代码如下:
#include <stdio.h>
#define NDEBUG
#include <assert.h>

用法总结与注意事项: