现在的位置: 首页 > 综合 > 正文

assert.h

2019年11月22日 ⁄ 综合 ⁄ 共 1254字 ⁄ 字号 评论关闭

 

assert.h

assert.h是c标准库的一个头文件,该头文件的主要目的就是提供一个assert的宏定义,该宏的主要作用就是加强在程序中critical places的断言,推崇在程序调试的过程中用assert,但是在一个最终的程序中不应该出现assert,不是出现问题就报错然后exit出来,而是要能很好的处理错误。下面看如何定义assert这个宏的:
/***
*assert.h - define the assert macro
*
* Copyright (c) 1985-1997, Microsoft Corporation. All rights reserved.
*
*Purpose:
* Defines the assert(exp) macro.
* [ANSI/System V]
*
* [Public]
*
****/

#if !defined(_WIN32) && !defined(_MAC)
#error ERROR: Only Mac or Win32 targets supported!
#endif

 

/* Define _CRTIMP */

#ifndef _CRTIMP
#ifdef _DLL
#define _CRTIMP __declspec(dllimport)
#else /* ndef _DLL */
#define _CRTIMP
#endif /* _DLL */
#endif /* _CRTIMP */

/* Define __cdecl for non-Microsoft compilers */

#if ( !defined(_MSC_VER) && !defined(__cdecl) )
#define __cdecl
#endif

/* Define _CRTAPI1 (for compatibility with the NT SDK) */

#ifndef _CRTAPI1
#if _MSC_VER >= 800 && _M_IX86 >= 300
#define _CRTAPI1 __cdecl
#else
#define _CRTAPI1
#endif
#endif

#undef assert

#ifdef NDEBUG

#define assert(exp) ((void)0)

#else

#ifdef __cplusplus
extern "C" {
#endif

_CRTIMP void __cdecl _assert(void *, void *, unsigned);

#ifdef __cplusplus
}
#endif

#define assert(exp) (void)( (exp) || (_assert(#exp, __FILE__, __LINE__), 0) )

#endif /* NDEBUG */

assert只是对所给的表达式求值,就像if判断语句中一样,然后如果该值为真则正常运行,否则报错,并调用abort(),产生异常中断,exit出来。通过代码可以看出,该宏可以屏蔽掉,只需在包含assert.h之前#define NDEBUG,想开再#undef,也可以看出预处理带来的方便。所谓的预处理就是在程序编译前由预处理程序进行对前面加#的实体进行预处理,包括导入头文件等等。。

抱歉!评论已关闭.