#assert
#if __STDC_VERSION__ >= 202311L
# define __STDC_VERSION_ASSERT_H__ 202311L
# ifdef NDEBUG
# define assert(...) ((void)0)
# else
# define assert(...) /* 具体实现定义 */
# endif
#else
# ifdef NDEBUG
# define assert(condition) ((void)0)
# else
# define assert(condition) /* 具体实现定义 */
# endif
#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
,则应当通过条件语句进行错误处理以提高程序的健壮性。
#推荐阅读
#参考标准
- C23 standard (ISO/IEC 9899:2024):
- 7.2.2.1 The assert macro (p: 196)
- C17 standard (ISO/IEC 9899:2018):
- 7.2.1.1 The assert macro (p: 135)
- 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