Chinaunix首页 | 论坛 | 博客
  • 博客访问: 519684
  • 博文数量: 96
  • 博客积分: 2102
  • 博客等级: 上尉
  • 技术积分: 1695
  • 用 户 组: 普通用户
  • 注册时间: 2012-04-11 22:12
文章分类

全部博文(96)

文章存档

2014年(2)

2012年(94)

分类: C/C++

2012-04-21 10:23:12

       头文件的唯一目的是提供assert的定义。
       在程序关键的部位可以使用该宏来断言,如果断言被证明为非真,我们希望程序在标准流输出一句适当的提
示信息。并且适时的终止。
      如果在包含assert.h的前面没有定义NDEBUG,则该头文件将宏定活动形式,即:可以展开为一个表达式,测试断言是否正确, 如果正确则继续执行,否则输出错误信息,并且终止程序。
 例子;

点击(此处)折叠或打开

  1. 没有定义NDEBUG
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #include<assert.h>
  5. int main()
  6. {
  7.     printf("1 ok hello \n");
  8.     assert(1==4);
  9.     printf("2 ok exit \n");
  10.     return 0;
  11. }
结果:
**************************************************************************************************
1 ok hello
assert_h_ex_nodebug: assert_h_ex.c:7: main: Assertion `1==4' failed.
已放弃
**************************************************************************************************

点击(此处)折叠或打开

  1. 定义NDEBUG
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #define NDEBUG
  5. #include<assert.h>
  6. int main()
  7. {
  8.     printf("1 ok hello \n");
  9.     assert(1==4);;
  10.    printf("2 ok exit \n");
  11.     return 0;
  12. }
结果:
********************************************************************************************************************************
1 ok hello
2 ok exit
********************************************************************************************************************************
原理:
  1. #define assert(test) if(!(test))\
  2.     fprintf(stderr,"the failed : %s file %s ,line %i\n",#test, __FILE__,__LINE__);\
  3.     abort();
模拟:

点击(此处)折叠或打开

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. //#define NDEBUG
  4. //#include<assert.h>
  5. #define Assert(test) if(!(test)) fprintf(stderr,"Assertion failed: %s, file %s, line %i\n", #test, __FILE__, __LINE__);abort()
  6. int main()
  7. {
  8.     printf("1 ok hello \n");
  9.     Assert(1==4);
  10.     printf("2 ok exit \n");
  11.     return 0;
  12. }
结果:
*************************************************************************************************
1 ok hello
Assertion failed: 1==4, file assert_h_ex.c, line 9
已放弃
**************************************************************************************************
阅读(1565) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~