C语言中assert的用法

这个源文件是i386-pc-mingw32中的GCC 4.5.0下包含的。

 1 * assert.h
 2 
 3   * This file has no copyright assigned and is placed in the Public Domain.
 4 
 5   * This file is a part of the mingw-runtime package.
 6 
 7   * No warranty is given; refer to the file DISCLAIMER within the package.
 8 
 9   *
10 
11   * Define the assert macro for debug output.
12 
13   *
14 
15   */
16 
17   /* We should be able to include this file multiple times to allow the assert
18 
19   macro to be enabled/disabled for different parts of code.  So don't add a
20 
21   header guard.  */
22 
23   #ifndef RC_INVOKED
24 
25   /* All the headers include this file. */
26 
27   #include <_mingw.h>
28 
29   #undef assert
30 
31   #ifdef __cplusplus
32 
33   extern "C" {
34 
35   #endif
36 
37   #ifdef NDEBUG
38 
39   /*
40 
41   * If not debugging, assert does nothing.
42 
43   */
44 
45   #define assert(x) ((void)0)
46 
47   #else /* debugging enabled */
48 
49   /*
50 
51   * CRTDLL nicely supplies a function which does the actual output and
52 
53   * call to abort.
54 
55   */
56 
57   _CRTIMP void __cdecl __MINGW_NOTHROW _assert (const char*, const char*, int) __MINGW_ATTRIB_NORETURN;
58 
59   /*
60 
61   * Definition of the assert macro.
62 
63   */
64 
65   #define assert(e)       ((e) ? (void)0 : _assert(#e, __FILE__, __LINE__))
66 
67   #endif /* NDEBUG */
68 
69   #ifdef __cplusplus
70 
71   }
72 
73   #endif
74 
75   #endif /* Not RC_INVOKED */

  该头文件中给我们提供的东西是非常简单的,主要就是一个assert宏。对其功能与说明借引自《C++函数库查询辞典》中的描述如下:

  说明:

  assert宏能测试传入表达式的真假值,当表达式为真(true),则不会有任何反应;当表达式为假(false),则函数将输出错误信息,并中断程序的执行。

  功能:

  assert宏可以用来判断某表达式的真假值,并在程序执行的过程中实时响应错误信息,因此在程序开发的过程中,常常被用来作程序纠错的工具,当程序开发完成,只需要在加载头文件前面,利用#define指令定义NDEBUG这个关键字,则所有assert都会失效,源程序不需做任何修改。

  当传入的表达式为真,则assert不会有任何响应;当表达式为假时,assert函数会显示出发生错误的表达式、源代码文件名以及发生错误的程序代码行数,并调用abort函数,结束程序执行。

教你写一个C的assert宏

     在C中 , 相信assert这个断言是用的最频繁的宏之一,特别是在我们找BUG的时候,多用一些断言可以让我们更靠近出错的代码,不多说,进入我们的主题,写出一个assert宏来。

  首先我们都知道,assert在debug版下是有效的,在release版中assert是无效的,那么我们应该如何实现这一功能呢?实际上在release的版本中系统定义了NDBUG这个宏常量,当然在debug中没有定义这个宏常量,所以在定义这个宏之前检查是否定义过NDBUG这个宏就可以知道是debug版还是release版了,见下面的代码:

1 #if !defined(NDBUG)
2  #define assert(p)        /*这里写上宏的代码*/    
3  #else
4  #define assert(p) 
5  #endif

现在我们继续实现的assert , 我们都知道断言要是失败了,要输出失败位置所在文件的文件名 , 和行号 , 当然输出应该重定向到标准出错里面。

__FILE__记录了当前执行的文件名。

__LINE__记录当前执行的行号。

stderr是标准出错。

当然断言要是失败的话 , 调用abort终止程序的执行 , 代码实现如下。

1 #if !defined(NDBUG)
2   #define assert(p)    if(!(p)){fprintf(stderr,\
3          "Assertion failed: %s, file %s, line %d\n",\
4          #p, __FILE__, __LINE__);abort();}     
5   #else
6   #define assert(p) 
7   #endif

好了一个C的assert宏就完成了。

 

 

posted @ 2012-07-30 14:10  软件小书童  阅读(1941)  评论(0)    收藏  举报