Assert(断言实现机制深入剖析)

言前后最好空一格[编程风格的问题,按你自已的喜好,适合自已就最好]。断言只是用来检查程序的逻辑正确性,不能代替条件替换。断言比printf语句这种形式的打印好使

断言(assert)的作用是用来判断程序运行的正确性,确保程序运行的行为与我们理解的一致。其调用形式为assert(logic expression),如果逻辑表达式为假,则调用abort()终止程序的运行。

查看MSDN帮助文档,可以得到assert的解释信息如下:

复制代码 代码如下:

The ANSI assert macro is typically used to identify logic errors during program development, by implementing the expression argument to evaluate to false only when the program is operating incorrectly. After debugging is complete, assertion checking can be turned off without modifying the source file by defining the identifier NDEBUG. NDEBUG can be defined with a /D command-line option or with a #define directive. If NDEBUG is defined with #define, the directive must appear before ASSERT.H is included.

翻译过来大概意思就是assert是通过判断其参数的真假来标识程序的逻辑错误,调试结束后可以通过定义NDEBUG来关闭assert断言。

查看include/assert.h头文件可以得到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(断言实现机制深入剖析)的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » C语言