作为初学者,以前学过的基本函数中没有接触过assert,今天偶然见到了assert函数,就在这里尝试使用assert函数。
首先函数的原型是:void assert(expression),如果assert函数中的expression为真,就继续执行下面的函数,如果为假,就中断跳出,并且在屏幕上输出中断信息。
函数存在于头文件assert.h中。
关于assert函数的有效性
如果在#include <assert.h>之前,输入了#define NDEBUG就可以使assert函数在程序中失效。
示例
(1)expression为真。
我们写一个简单的程序:
#include <stdio.h>
#include<stdlib.h>
#include <assert.h>
int main()
{
int i = 1;
assert(i);
printf("pass!");
return 0;
}
运行结果:
(2)expression为假。
沿用上面的程序,但是将i的值改为0:
#include <stdio.h>
#include<stdlib.h>
#include <assert.h>
int main()
{
int i = 0;
assert(i);
printf("oifjeoj");
return 0;
}
运行结果
(3)只用#define NDEBUG
按照上述说明,如果在#include <assert.h>之前插入这行代码,那么assert就失效,程序仍然会输出“pass!”。