打算趁留在学校的最后一段时间好好补习一下一直以来都忽略掉的C/C++标准库,大概就是以头文件为单位了。以一个最简单的头文件入手,然后逐渐展开来……第一个头文件当然非assert.h莫属了。这个范例是i386-pc-mingw32中的GCC 4.5.0下包含的。
该头文件中给我们提供的东西是非常简单的,主要就是一个assert宏。对其功能与说明借引自《C++函数库查询辞典》中的描述如下:
cpp;collapse:true;;gutter:false;
/*
* assert.h
* This file has no copyright assigned and is placed in the Public Domain.</p>
<ul>
<li>
<p>This file is a part of the mingw-runtime package.</p>
</li>
<li>
<p>No warranty is given; refer to the file DISCLAIMER within the package.</p>
</li>
</ul>
<p>*
* Define the assert macro for debug output.</p>
<p>*
*/</p>
<p>/<em> 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. </em>/</p>
<h1>ifndef RC_INVOKED</h1>
<p>/<em> All the headers include this file. </em>/</p>
<h1>include</h1>
<h1>undef assert</h1>
<h1>ifdef __cplusplus</h1>
<p>extern "C" {</p>
<h1>endif</h1>
<h1>ifdef NDEBUG</h1>
<p>/*
* If not debugging, assert does nothing.</p>
<p>*/</p>
<h1>define assert(x) ((void)0)</h1>
<h1>else /<em> debugging enabled </em>/</h1>
<p>/*
* CRTDLL nicely supplies a function which does the actual output and
* call to abort.</p>
<p><em>/
_CRTIMP void __cdecl __MINGW_NOTHROW _assert (const char</em>, const char*, int) __MINGW_ATTRIB_NORETURN;</p>
<p>/*
* Definition of the assert macro.</p>
<p>*/</p>
<h1>define assert(e) ((e) ? (void)0 : _assert(#e, <strong>FILE</strong>, <strong>LINE</strong>))</h1>
<h1>endif /<em> NDEBUG </em>/</h1>
<h1>ifdef __cplusplus</h1>
<p>}</p>
<h1>endif</h1>
<h1>endif /<em> Not RC_INVOKED </em>/</h1>
<pre><code>
说明:
assert宏能测试传入表达式的真假值,当表达式为真(true),则不会有任何反应;当表达式为假(false),则函数将输出错误信息,并中断程序的执行。
功能:
assert宏可以用来判断某表达式的真假值,并在程序执行的过程中实时响应错误信息,因此在程序开发的过程中,常常被用来作程序纠错的工具,当程序开发完成,只需要在加载头文件前面,利用#define指令定义NDEBUG这个关键字,则所有assert都会失效,源程序不需做任何修改。
当传入的表达式为真,则assert不会有任何响应;当表达式为假时,assert函数会显示出发生错误的表达式、源代码文件名以及发生错误的程序代码行数,并调用abort函数,结束程序执行。
使用范例:
;gutter:false;
// #define NDEBUG // don’t use assert
#include
#include
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…
如此一来,其起作用的时机及功能就比较清晰了。
Original: https://www.cnblogs.com/mazhuang/archive/2009/12/30/assert_h.html
Author: mzlogin
Title: [学习标准库]assert.h
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/572796/
转载文章受原作者版权保护。转载请注明原作者出处!