assert巨集的原型定義在<assert.h>中,其作用是如果它的條件返回錯誤,則終止程式執行,原型定義:
#include <assert.h>
void assert( int expression );

assert的作用是 計算運算式 expression ,如果其值為假(即為0),那麼它先向stderr列印一條出錯資訊,
然後通過呼叫 abort 來終止程式執行。

請看下面的程式清單badptr.c

[cpp] view plain copy

 print?

  1. #include <stdio.h>  
  2. #include <assert.h>  
  3. #include <stdlib.h>  
  4.   
  5. int main( void )  
  6. {  
  7.        FILE *fp;  
  8.       
  9.        fp = fopen( "test.txt""w" );//以可寫的方式打開一個檔,如果不存在就建立一個同名檔  
  10.        assert( fp );                           //所以這裡不會出錯  
  11.        fclose( fp );  
  12.       
  13.        fp = fopen( "noexitfile.txt""r" );//以唯讀的方式打開一個檔,如果不存在就打開檔失敗  
  14.        assert( fp );                           //所以這裡出錯  
  15.        fclose( fp );                           //程式永遠都執行不到這裡來  
  16.   
  17.        return 0;  
  18. }  

 

巨集名: assert

: 測試一個條件並可能使程式終止

: void assert(int test);

程式例:

 

[cpp] view plain copy

 print?

  1. #include <assert.h>  
  2. #include <stdio.h>  
  3. #include <stdlib.h>  
  4. struct ITEM {  
  5.   int key;  
  6.   int value;  
  7. };  
  8.    
  9. /* add item to list, make sure list is not null */  
  10. void additem(struct ITEM *itemptr) {  
  11.   assert(itemptr != NULL);  
  12.   /* add item to list */  
  13. }  
  14.    
  15. int main(void)  
  16. {  
  17.   additem(NULL);  
  18.   return 0;  
  19. }  

 

assert() 巨集用法

注意:assert是巨集,而不是函數。在Cassert.h標頭檔中。

assert巨集的原型定義在<assert.h>中,其作用是如果它的條件返回錯誤,則終止程式執行,原型定義:

[cpp] view plain copy

 print?

  1. #include <assert.h>  
  2. void assert( int expression );  


assert的作用是先計算運算式expression,如果其值為假(即為0),那麼它先向標準錯誤流stderr列印一條出錯資訊,然後通過呼叫abort來終止程式執行;否則,assert()無任何作用。巨集assert()一般用於確認程式的正常操作,其中運算式構造無錯時才為真值。完成除錯後,不必從原始程式碼中刪除assert()語句,因為巨集NDEBUG有定義時,巨集assert()的定義為空。

arrow
arrow
    文章標籤
    assert
    全站熱搜

    立你斯 發表在 痞客邦 留言(0) 人氣()