打算趁留在学校的最后一段时间好好补习一下一直以来都忽略掉的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...
如此一来,其起作用的时机及功能就比较清晰了。