C++ assert()函數(shù)應(yīng)用方式剖析
作為一個經(jīng)驗(yàn)豐富的編程人員來說,對于C++編程語言應(yīng)該不會陌生的,它的應(yīng)用可以幫助我們輕松的實(shí)現(xiàn)各種功能需求。在這里我們會對C++ assert()函數(shù)的一些基本應(yīng)用做一個詳細(xì)介紹。
assert宏的原型定義在< assert.h>中,其作用是如果它的條件返回錯誤,則終止程序執(zhí)行,原型定義:
- #include < assert.h>
- void assert( int expression );
C++ assert()函數(shù)的作用是現(xiàn)計(jì)算表達(dá)式 expression ,如果其值為假(即為0),那么它先向stderr打印一條出錯信息,然后通過調(diào)用 abort 來終止程序運(yùn)行。請看下面的程序清單badptr.c:
- #include < stdio.h>
- #include < assert.h>
- #include < stdlib.h>
- int main( void )
- {
- FILE *fp;
- fp = fopen( "test.txt", "w" );
//以可寫的方式打開一個文件,如果不存在就創(chuàng)建一個同名文件- assert( fp ); //所以這里不會出錯
- fclose( fp );
- fp = fopen( "noexitfile.txt", "r" );
//以只讀的方式打開一個文件,如果不存在就打開文件失敗- assert( fp ); //所以這里出錯
- fclose( fp ); //程序永遠(yuǎn)都執(zhí)行不到這里來
- return 0;
- }
- [root@localhost error_process]# gcc badptr.c
- [root@localhost error_process]# ./a.out
- a.out: badptr.c:14: main: Assertion `fp' failed.
已放棄
使用C++ assert()函數(shù)的缺點(diǎn)是,頻繁的調(diào)用會極大的影響程序的性能,增加額外的開銷。 在調(diào)試結(jié)束后,可以通過在包含#include < assert.h>的語句之前插入 #define NDEBUG 來禁用assert調(diào)用,示例代碼如下:
- #include < stdio.h>
- #define NDEBUG
- #include < assert.h>
以上就是對C++ assert()函數(shù)的相關(guān)介紹。
【編輯推薦】