头文件<assert.h>

头文件<assert.h>的目的就是提供宏assert的定义。在程序中可以用这个宏来断言,如果断言是真,则继续执行。如果断言为假,则在标准输入流中输出一条提示信息,并执行终止异常。

通过宏DEBUG控制断言是否有效:如果程序中包含<assert.h>的地方没有定义NDEBUG,则宏assert为活动形式;如果程序中包含<assert.h>的地方定义了NDEBUG,则宏assert为静止形式。即:

当存在

#define NDEBUG

#include <assert.h>

时,下面程序中出现的assert(x==y)不执行任何操作

当存在

#undef NDEBUG

#include <assert.h>

时,下面程序中出现的assert(x==y)不成立时会向输出错误并执行终止异常。

 

例1:

#define NDEBUG  //在取消声明以前的代码段中assert均为静止形式
#include <assert.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>

static int val=0;

static void field_abort(int sig)
{
if(val==1)
{
puts("SUCCESS TESTING <assert.h>");
exit(EXIT_SUCCESS);
}
else
{
puts("FAILURE TESTING <assert.h>");
exit(EXIT_FAILURE);
}
}

static void dummy()

{
int i=0;

assert(i==0);
assert(i==1);  //assert为静止形式,故不会发生异常。
}

#undef NDEBUG  //取消NDEBUG声明,在define NDEBUG以前assert都是活动形式。
#include <assert.h>

int main ()
{
assert(signal(SIGABRT,&field_abort)!=SIG_ERR);
dummy();
++val;
fputs("Sample assertion failure message -- \n",stderr);
assert(val==0);
puts("FAILURE TESTING <assert.h>");
return(EXIT_FAILURE);
}

 

执行结果是:

Sample assertion failure message --
t: testAssert.c:41: main: Assertion `val==0' failed.
SUCCESS TESTING <assert.h>

 

例2:

#include <assert.h>  //没有define NDEBUG,故在声明以前assert都是活动形式。
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>

static int val=0;

static void field_abort(int sig)
{
if(val==1)
{
puts("SUCCESS TESTING <assert.h>");
exit(EXIT_SUCCESS);
}
else
{
puts("FAILURE TESTING <assert.h>");
exit(EXIT_FAILURE);
}
}

static void dummy()

{
int i=0;

assert(i==0);
assert(i==1);  //活动形式,故会终止
}

#define NDEBUG
#include <assert.h>

int main ()
{
assert(signal(SIGABRT,&field_abort)!=SIG_ERR);
dummy();
++val;
fputs("Sample assertion failure message -- \n",stderr);
assert(val==0);
puts("FAILURE TESTING <assert.h>");
return(EXIT_FAILURE);
}

 

执行结果是:

t: testAssert.c:28: dummy: Assertion `i==1' failed.
Aborted

转载于:https://www.cnblogs.com/Mr-Wenyan/p/7213809.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值