#assert
#ifdef NDEBUG
#define assert(condition) ((void)0)
#else
#define assert(condition) /* 由具体实现定义 */
#endif
assert
检查 condition
是否等于 0
若
condition
等于 0,在stderr
上输出诊断信息并调用 abort 中止程序若
condition
不等于 0,则代码继续正常执行
如果宏 NDEBUG
被定义,则 assert
被屏蔽,不执行任何操作。
示例:
#include <stdio.h>
// #define NDEBUG // 在引入 assert.h 之前定义 NDEBUG 可以屏蔽 assert
#include <assert.h>
#include <math.h>
int main(void)
{
double x = -1.0;
assert(x > 0.0); // 断言 x 大于 0,因为对数函数的定义域为 x > 0
printf("log(x) = %f\n", log(x));
return 0;
}
运行结果:
user@host:~ $ gcc main.c -lm
user@host:~ $ ./a.outa.out: main.c:10: main: Assertion `x > 0.0' failed. Aborted (core dumped)
在该示例中,我们要计算 x
的对数,而对数函数的定义域为 x > 0
,因此通过 assert
断言 x > 0
。
在开发调试阶段,如果发现存在 x <= 0
的情况,assert
会输出诊断信息并调用 abort 中止程序,便于快速发现问题。
在保障 x <= 0
的情况不会再出现后,发布阶段通过定义 NDEBUG
宏屏蔽 assert
以降低开销提升程序性能。
如果无法保障 x > 0
,则应当通过条件语句进行错误处理以提高程序的健壮性。