assert宏的原型定义在<assert.h>中,其作用是如果它的条件返回错误,则终止程序执行,原型定义:
#include <assert.h>
void assert( int expression );
assert的作用是现计算表达式 expression ,如果其值为假,那么它先向stderr打印一条出错信息,然后通过调用 abort 来终止程序运行
试看如下代码:
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
int main()
{
FILE *fp;
fp = fopen( "test.txt", "w" );//以可写的方式打开一个文件,如果不存在就创建一个同名文件
assert( fp ); //所以这里不会出错
fclose( fp );
fp = fopen( "noexitfile.txt", "r" );//以只读的方式打开一个文件,如果不存在就打开文件失败
assert( fp );//所以这里出错
fclose( fp );//程序永远都执行不到这里来
return 0;
}
缺点:频繁的调用会极大的影响程序的性能,增加额外的开销。
程序中关键的地方可以通过assert这个宏来断言。如果断言非真,程序停止,标准错误输出一条具体的错误信息。
在实战中,程序直接停止是很不好的现象,因此断言只在调试程序使用。
————————————————————————————————————————————————————————
(1)NDEBUG宏
#include <stdio.h>
#define NDEBUG
#include <assert.h>
int main()
{
int i = 0;
assert(i == 0);
print("assert不会起作用")
return 0;
}
(2)打开断言
#undef NDEBUG
#include<assert.h>
#include <stdio.h>
#undef NDEBUG
#include <assert.h>
void func1()
{
int i = 0;
assert(i == 0);
assert(i == 1);
}
int main()
{
func1();
printf("hello world\n");
return 0;
}
输入结果:
(3)关闭断言
#define NDEBUG
#include<assert.h>
#include <stdio.h>
#define NDEBUG
#include <assert.h>
void func2()
{
int i = 0;
assert(i == 0);
assert(i == 1);
}
int main()
{
func2();
printf("hello world\n");
return 0;
}
输出结果: