[學習標準庫]assert.h

  打算趁留在學校的最後一段時間好好補習一下一直以來都忽略掉的C/C++標準庫,大概就是以頭文件爲單位了。以一個最簡單的頭文件入手,然後逐漸展開來……第一個頭文件當然非assert.h莫屬了。這個範例是i386-pc-mingw32中的GCC 4.5.0下包含的。

  該頭文件中給我們提供的東西是非常簡單的,主要就是一個assert宏。對其功能與說明借引自《C++函數庫查詢辭典》中的描述如下:
 

/* 
 * assert.h
 * This file has no copyright assigned and is placed in the Public Domain.
 * This file is a part of the mingw-runtime package.
 * No warranty is given; refer to the file DISCLAIMER within the package.
 *
 * Define the assert macro for debug output.
 *
 */

/* We should be able to include this file multiple times to allow the assert
   macro to be enabled/disabled for different parts of code.  So don't add a
   header guard.  */ 

#ifndef RC_INVOKED

/* All the headers include this file. */
#include <_mingw.h>

#undef assert

#ifdef	__cplusplus
extern "C" {
#endif

#ifdef NDEBUG
/*
 * If not debugging, assert does nothing.
 */
#define assert(x)	((void)0)

#else /* debugging enabled */

/*
 * CRTDLL nicely supplies a function which does the actual output and
 * call to abort.
 */
_CRTIMP void __cdecl __MINGW_NOTHROW _assert (const char*, const char*, int) __MINGW_ATTRIB_NORETURN;

/*
 * Definition of the assert macro.
 */
#define assert(e)       ((e) ? (void)0 : _assert(#e, __FILE__, __LINE__))

#endif	/* NDEBUG */

#ifdef	__cplusplus
}
#endif

#endif /* Not RC_INVOKED */

說明:
  assert宏能測試傳入表達式的真假值,當表達式爲真(true),則不會有任何反應;當表達式爲假(false),則函數將輸出錯誤信息,並中斷程序的執行。

功能:
  assert宏可以用來判斷某表達式的真假值,並在程序執行的過程中實時響應錯誤信息,因此在程序開發的過程中,常常被用來作程序糾錯的工具,當程序開發完成,只需要在加載頭文件前面,利用#define指令定義NDEBUG這個關鍵字,則所有assert都會失效,源程序不需做任何修改。
  當傳入的表達式爲真,則assert不會有任何響應;當表達式爲假時,assert函數會顯示出發生錯誤的表達式、源代碼文件名以及發生錯誤的程序代碼行數,並調用abort函數,結束程序執行。

使用範例:

// #define NDEBUG // don't use assert
#include <assert.h>
#include <iostream>
int main()
{
    int i = 0;
    std::cout << "before assert(i==0)" << std::endl;
    assert(i==0);
    std::cout << "before assert(i==1)" << std::endl;
    assert(i==1);
    std::cout << "after assert(i==1)" << std::endl;
    return 0;
}

  此程序最後產生的輸出爲:
C:\WINDOWS\system32\cmd.exe /c a.exe

before assert(i==0)

before assert(i==1)

Assertion failed: i==1, file test.cpp, line 11This application has requested the Runtime to terminate it in an unusual way.Please contact the application's support team for more information.

shell returned 3

Hit any key to close this window...
  如此一來,其起作用的時機及功能就比較清晰了。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章