在程序关键的部位可以使用该宏来断言,如果断言被证明为非真,我们希望程序在标准流输出一句适当的提
示信息。并且适时的终止。
如果在包含assert.h的前面没有定义NDEBUG,则该头文件将宏定活动形式,即:可以展开为一个表达式,测试断言是否正确, 如果正确则继续执行,否则输出错误信息,并且终止程序。
例子;
点击(此处)折叠或打开
- 没有定义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
已放弃
**************************************************************************************************