C語言中的assert用法
assert宏的原型定義在中,其作用是如果它的條件返回錯誤,則終止程序執(zhí)行,歡迎大家閱讀!更多相關(guān)信息請關(guān)注相關(guān)欄目!
assert宏的原型定義在中,其作用是如果它的條件返回錯誤,則終止程序執(zhí)行,原型定義:
#include void assert( int expression );assert的作用是現(xiàn)計算表達式 expression ,如果其值為假(即為0),那么它先向stderr打印一條出錯信息,
然后通過調(diào)用 abort 來終止程序運行。
請看下面的程序清單badptr.c:
復(fù)制代碼 代碼如下:
#include
#include
#include
int main( void )
{
FILE *fp;
fp = fopen( "test.txt", "w" );/pic/p>
assert( fp ); /pic/p>
fclose( fp );
fp = fopen( "noexitfile.txt", "r" );/pic/p>
assert( fp ); /pic/p>
fclose( fp ); /pic/p>
return 0;
}
宏名: assert功 能: 測試一個條件并可能使程序終止
用 法: void assert(int test);
程序例:
復(fù)制代碼 代碼如下:
#include
#include
#include
struct ITEM {
int key;
int value;
};
/* add item to list, make sure list is not null */
void additem(struct ITEM *itemptr) {
assert(itemptr != NULL);
/* add item to list */
}
int main(void)
{
additem(NULL);
return 0;
}
assert() 宏用法注意:assert是宏,而不是函數(shù)。在C的assert.h頭文件中。assert宏的原型定義在中,其作用是如果它的條件返回錯誤,則終止程序執(zhí)行,原型定義:
復(fù)制代碼 代碼如下:
#include
void assert( int expression );
assert的作用是先計算表達式expression,如果其值為假(即為0),那么它先向標準錯誤流stderr打印一條出錯信息,然后通過調(diào)用abort來終止程序運行;否則,assert()無任何作用。宏assert()一般用于確認程序的正常操作,其中表達式構(gòu)造無錯時才為真值。完成調(diào)試后,不必從源代碼中刪除assert()語句,因為宏NDEBUG有定義時,宏assert()的定義為空。
【C語言中的assert用法】相關(guān)文章:
C語言中assert的用法01-29
C語言中assert用法02-26
C語言中assert的用法講解03-19
C語言中assert的用法有什么12-16
C語言中assert的用法有哪些05-13
C語言assert的用法07-29
C語言assert用法05-20
assert用法(C語言)03-24
C語言assert的用法有哪些04-20