头文件<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

posted @ 2017-07-20 18:38  第五  阅读(2727)  评论(0编辑  收藏  举报