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