assert很多时候到会用到,下面了解下assert的实现和用法

在C标准库中,assert的实现是用宏来实现的,并不是用函数,它在#include<assert.h>这标准C头文件

1、实现:宏assert是如何实现的呢?可以查看assert.h的代码,我查看的是mingw中的代码

#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

很明显的看到 #define assert(e)  ((e) ? (void)0 : _assert(#e, __FILE__, __LINE__))

assert()它就是一个宏,如果表达式e为真,则为(void)0;表达式e为假,则调用_assert(#e, __FILE__, __LINE__)这函数

_assert(#e, __FILE__, __LINE__)具体实现类似以下的实现

 void _assert(const char *mesg, const char *file, int line)
 {
       printf("%s, %s, %d\n", mesg, file, line); 
       abort();
 }

所以当表达式e为假的时候,函数abort()被用来终止程序运行.

2、用法

一般在在源文件中加上

#include <assert.h>或者

#undef NDEBUG

#include <assert.h>

取消的时候用

#define NDEBUG 

#include <assert.h>  -#define NDEBUG应在#include <assert.h>前头, 这样才是正确的.看源码就知道了

assert(表达式);

示范: int a = 1; assert(a);

 

posted on 2014-11-17 16:27  Dscxy  阅读(2047)  评论(0编辑  收藏  举报