C 语言 assert() 是一个断言宏:如果表达式为假,程序输出错误信息并终止。
原型
void assert(int expression);表达式为真(非 0)时什么都不做;为假时打印表达式、文件名、行号并调用 abort() 终止程序。
参数
expression- 要断言的表达式,为假时终止程序。
示例
#include <stdio.h>
#include <assert.h>
int main() {
int x = 10;
assert(x > 0); // 通过
printf("x = %d\n", x);
int y = -5;
assert(y > 0); // 失败,程序终止
printf("这行不会执行\n");
return 0;
}输出:
x = 10
Assertion failed: (y > 0), function main, file test.c, line 11.注意事项
编译时定义 NDEBUG 宏可禁用 assert(发布版)。assert 用于调试期,不要用它做运行时错误处理。