頭文件


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM