0%

C/C++编程—断言(Assert)

断言是指在开发期间使用的、让程序运行时进行自检的代码。断言为真,表示程序运行正常,断言为假,则意味着程序中出现了意料之外的错误。

一个断言通常含有两个参数:一个描述假设为真时的布尔表达式,一个断言为假时需要显示的信息。
C++标准中的assert宏并不支持文本信息,可以使用C++宏改进ASSERT。

1
2
3
4
5
6
7
8
9
#define ASSERT(condition, message)
{
if(!(condition))
{
LogError("Assert failed:",
#condition, message);
exit(EXIT_FAILURE);
}
}

频繁的调用asset()会极大影响程序的性能,增加额外的开销。在调试结束以后,可以通过在包含#include <assert.h>的语句前插入#define NDEBUG来禁用assert()调用。

1
2
3
4
5
6
7
8
9
10
11
#ifdef _DEBUG
#define ASSERT(condition)
if(!(condition))
{
fflush(stdout);
fprintf(stderr,"\nAssert failed:%s, lint %u\n",__FILE__, __LINE__);

}
#else
#define ASSERT(condition) NULL
#endif

参考文献 & 资源链接