3.如何用好ASSERT之无价之宝

本文介绍了一种自定义Assert宏的方法,通过增加一个'总是忽略'的选项,使开发者能够在遇到频繁触发的断言时选择忽略,从而提高调试效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前我们了解了Assert的基本用法和怎么样定制自己的Assert宏。

但是遇到以下代码,会感觉到很烦呢?手都要按断呢。

#include <assert.h>
#include <string.h>
#include <Windows.h>
bool CustomAssertFunction(bool isfalse,char* description,char* filepath,int line)//Assert执行的函数
{
	if(true == isfalse)
		return false;
	printf("需要调试的位置为 %s 中的 %d 行\n",filepath,line);
	if(IDOK== MessageBoxA(0,description,"Assert调试",MB_OKCANCEL))
		return true;
	else return false;
}
#if defined( _DEBUG )//如果在debug模式
//定义assert宏,用if判断是否进行{ int 3 }调试
#define Assert(exp,description) \
	if(CustomAssertFunction(int(exp),description,__FILE__, __LINE__)) \
{_asm{int 3}}
#else
#define Assert(exp,description)
#endif
int _tmain(int argc, _TCHAR* argv[])
{
	for(int i=0;i < 10 ;i++)
	{
		Assert(i==10,"i is not 10");
	}
}

是的,遇到这样的问题,我们简直无能为力。因此,我们可以给Assert加上一个"总是忽略" 的选项。


#include <assert.h>
#include <string.h>
#include <Windows.h>
bool CustomAssertFunction(bool isfalse,char* description,char* filepath,int line,bool& ignoreAlways)//Assert执行的函数
{
	if(true == isfalse)
		return false;
	printf("需要调试的位置为 %s 中的 %d 行\n",filepath,line);
	UINT messageboxreturned=MessageBoxA(0,description,"Assert调试,终止则进行调试",MB_ABORTRETRYIGNORE);
	if(IDABORT== messageboxreturned)
		return true;
	else if(IDIGNORE==messageboxreturned)
		ignoreAlways=true;
	return false;
}

#if defined( _DEBUG )//如果在debug模式
//定义assert宏,用if判断是否进行{ int 3 }调试
#define Assert(exp,description)  {static bool ignoreAlways=false;if(!ignoreAlways){if(CustomAssertFunction(int(exp),description,__FILE__, __LINE__,ignoreAlways)) {_asm{int 3} }}}
#else
#define Assert(exp,description)
#endif
int _tmain(int argc, _TCHAR* argv[])
{
	for(int i=0;i < 10 ;i++)
	{
		Assert(i==10,"i is not 10");
	}
}



这样我们就可以忽略掉这个烦人的Assert了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值