赞
踩
assert.h是C标准函数库中的头文件。其中定义了assert()
宏用于程序调试。
在C标准函数库中,它是个非常特别的头文件,你可以将它引入数次以获得不同的效果,此效果依引入时是否以定义NDEBUG而定。
宏
assert()
是一个诊断宏,用于动态辨识程序的逻辑错误条件。其原型是: void assert( int expression);
如果宏的参数求值结果为非零值,则不做任何操作(no action);如果是零值,用宽字符(wide characters)打印诊断消息,然后调用abort()。诊断消息包括:
__FILE__
的值)__LINE__
的值)__func__
的值),这是 C99新增的特性诊断信息的显示目标依赖与被调用程序的类型。如果是控制台程序,诊断信息显示在stderr设备;如果是基于窗口的程序,assert()
产生一个Windows MessageBox来显示诊断信息。
程序可以屏蔽掉所有的assert()
而无需修改源代码。这只需要在命令行调用C语言的编译器时添加宏定义的命令行选项,定义DNDEBUG
宏;也可以在源程序程序引入<assert.h>
之前就使用#define NDEBUG
来定义宏。被屏蔽的assert()
甚至不对传递给它的参数表达式求值,因此使用assert()
时其参数表达式不能有副作用(side-effects).
例程:
- #include <stdio.h>
- #include <assert.h>
-
- int main (void)
- {
- FILE *fd;
-
- fd = fopen ("/home/user/file.txt", "r");
- assert (fd);
- fclose (fd);
-
- return 0;
- }
例程:
- //没有定义NDEBUG
-
- #include<stdio.h>
-
- #include<stdlib.h>
-
- #include<assert.h>
-
- int main()
-
- {
-
- printf("1 ok hello \n");
-
- assert(1==4);
-
- printf("2 ok exit \n");
-
- return 0;
-
- }
-

- 结果:
- **************************************************************************************************
- 1 ok hello
- assert_h_ex_nodebug: assert_h_ex.c:7: main: Assertion `1==4' failed.
- 已放弃
- **************************************************************************************************
-
- //定义NDEBUG
-
- #include<stdio.h>
-
- #include<stdlib.h>
-
- #define NDEBUG
-
- #include<assert.h>
-
- int main()
-
- {
-
- printf("1 ok hello \n");
-
- assert(1==4);;
-
- printf("2 ok exit \n");
-
- return 0;
-
- }
-

- 结果:
- ********************************************************************************************************************************
- 1 ok hello
- 2 ok exit
- ********************************************************************************************************************************
- 原理:
- #define assert(test) if(!(test))\
- fprintf(stderr,"the failed : %s file %s ,line %i\n",#test, __FILE__,__LINE__);\
- abort();
- 模拟:
-
- #include<stdio.h>
-
- #include<stdlib.h>
-
- //#define NDEBUG
-
- //#include<assert.h>
-
- #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;
-
- }

-
- 结果:
- *************************************************************************************************
- 1 ok hello
- Assertion failed: 1==4, file assert_h_ex.c, line 9
- 已放弃
- **************************************************************************************************
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。