C语言断言库assert.h提供了一些用于调试程序时进行断言的函数。如果断言失败,会输出错误消息并终止程序。
assert.h中主要的函数是assert(),其原型为:
void assert(int expression);
参数expression是一个要测试的表达式,如果表达式的值为0(假),assert()会输出错误消息并终止程序。如果表达式的值为非0(真),则assert()不做任何事情。
以下是一个使用assert()函数的示例代码:
#include <stdio.h>
#include <assert.h>
int main() {
int a = 5, b = 0;
assert(b != 0); // 断言b不为0,如果为0则输出错误消息并终止程序
printf("a/b = %d\n", a/b);
return 0;
}
在上面的代码中,我们使用assert()函数来断言b不为0。但是由于b的值为0,程序会输出错误消息并终止:
Assertion failed: b != 0, file assert_example.c, line 7
assert()宏接收一个整型表达式作为参数,如果表达式为假,就在标准错误stderr中写入一条错误信息,如测试名,文件名,行号等,并调用abort()终止程序
#include <stdio.h>
#include <assert.h>
int Div(int a, int b)
{
assert(b != 0);
return a / b;
}
int main()
{
printf("%d\n", Div(5, 0));
}
设程序名为test.c,编译出的可执行文件为te

文章介绍了C语言头文件assert.h中用于调试的assert()函数,当表达式为假时,程序会输出错误信息并终止。还提到了_C-static_assert()用于编译时断言,如果表达式为假,编译将失败。此外,NDEBUG宏可用于禁用assert()功能。

7252

被折叠的 条评论
为什么被折叠?



