设为首页 加入收藏

TOP

c标准函数库--->assert.h
2014-11-23 23:33:51 来源: 作者: 【 】 浏览:4
Tags:标准 函数 ---> assert.h

assert.h是C标准函数库中的头文件。其中定义了assert()宏用于程序调试。
在C标准函数库中,它是个非常特别的头文件,你可以将它引入数次以获得不同的效果,此效果依引入时是否以定义NDEBUG而定。


assert()是一个诊断宏,用于动态辨识程序的逻辑错误条件。其原型是: void assert( int expression);
如果宏的参数求值结果为非零值,则不做任何操作(no action);如果是零值,用宽字符(wide characters)打印诊断消息,然后调用abort()。诊断消息包括:
源文件名字 (在stdlib.h中声明的宏__FILE__的值)
所在的源文件的行号(在stdlib.h中声明的宏__LINE__的值)
所在的函数名 (在stdlib.h中声明的宏__func__的值),这是 C99新增的特性
求值结果为0的表达式
诊断信息的显示目标依赖与被调用程序的类型。如果是控制台程序,诊断信息显示在stderr设备;如果是基于窗口的程序,assert()产生一个Windows MessageBox来显示诊断信息。
程序可以屏蔽掉所有的assert()而无需修改源代码。这只需要在命令行调用C语言的编译器时添加宏定义的命令行选项,定义DNDEBUG宏;也可以在源程序程序引入之前就使用#define NDEBUG来定义宏。被屏蔽的assert()甚至不对传递给它的参数表达式求值,因此使用assert()时其参数表达式不能有副作用(side-effects).

例程:
[cpp]
#include
#include

int main (void)
{
FILE *fd;

fd = fopen ("/home/user/file.txt", "r");
assert (fd);
fclose (fd);

return 0;
}

例程:
[cpp]
//没有定义NDEBUG

#include

#include

#include

int main()

{

printf("1 ok hello \n");

assert(1==4);

printf("2 ok exit \n");

return 0;

}
[cpp]
结果:
**************************************************************************************************
1 ok hello
assert_h_ex_nodebug: assert_h_ex.c:7: main: Assertion `1==4' failed.
已放弃
**************************************************************************************************
[cpp]
//定义NDEBUG

#include

#include

#define NDEBUG

#include

int main()

{

printf("1 ok hello \n");

assert(1==4);;

printf("2 ok exit \n");

return 0;

}
[cpp]
结果:
********************************************************************************************************************************
1 ok hello
2 ok exit
********************************************************************************************************************************
[cpp]
原理:
#define assert(test) if(!(test))\

fprintf(stderr,"the failed : %s file %s ,line %i\n",#test, __FILE__,__LINE__);\

abort();
[cpp]
模拟:

#include

#include

//#define NDEBUG

//#include

#define Assert(test) if(!(test)) fprintf(stderr,"Assertion failed: %s, file %s, line %i\n", #test, __FILE__, __LINE__);abort()

int main()

{

printf("1 ok hello \n");

Assert(1==4);

printf("2 ok exit \n");

return 0;

}
[cpp]
结果:
*************************************************************************************************
1 ok hello
Assertion failed: 1==4, file assert_h_ex.c, line 9
已放弃
**************************************************************************************************

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇迷宫求解 下一篇单词统计

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: