在 C 语言的标准库 <assert.h>
中主要定义了一个宏函数 void assert (int expression);
,当函数的参数 expression
的值为 0
时,assert()
函数将会把调用 assert(expression);
语句所在的文件名、行号和 expression
等信息一起输出到标准输出流中,并调用 C 的 abort()
系统调用方法中止程序的执行,让程序员知道程序在这个地方出错了。因此,assert()
函数是专门为 debug 准备的:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int main()
{
int a = 12, b = 24;
assert(a > b);
printf("a is larger than b!\n");
return 0;
}
上述程序的输出如下所示:
Assertion failed: a > b, file G:\CLibLearning\main.c, line 9
此处,printf
语句将不再执行,因为运行到 assert
语句时程序就已经被中止退出。
当 debug 阶段已经全部结束时,不需要逐一把源代码中的调用 assert
的语句去掉,只需要在 #include <assert.h>
语句前添加宏 #define NDEBUG
即可以使得所有的 assert()
语句都失效:
#include <stdio.h>
#include <stdlib.h>
#define NDEBUG
#include <assert.h>
int main()
{
int a = 12, b = 24;
assert(a > b);
printf("a is larger than b!\n");
return 0;
}
上述程序将输出:
a is larger than b!