调用bool函数的时候如果函数return false。自动打印日志并return false,有兴趣可以拿来玩玩用

//调用bool函数假如返回false,我们经常需要打印日志,然后再有可能需要返回:


if(!BoolFunc()){
    printf("...");
    return false;
}


//本人比较懒,希望一步搞定:


DebugBoolFuncErrorReturn(BoolFunc());


// 以下是源代码

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;



bool DebugBoolFlag(const char *log1, const char *log2 = NULL);



bool DebugBoolFlag(const char *log1, const char *log2){
    printf("debug: %s make a error\n", log1);
    if(log2)
        printf("\t%s\n", log2);
    return false;
}



#define TOSTRING_HELPER(s) #s

#define TOSTRING(s) TOSTRING_HELPER(s)



# define LOCATION ":" __FILE__ ":" TOSTRING(__LINE__) " "


#define DebugBoolFuncNoReturnWithCustomLog(func, log2)  func ? true :  DebugBoolFlag(#func LOCATION, log2)

#define DebugBoolFuncNoReturn(func)  func ? true :  DebugBoolFlag(#func LOCATION)



#define DebugBoolFuncErrorReturnWithCustomLog(func, log2)   {\
     if(!func){\
        DebugBoolFlag(#func LOCATION, log2); \
        return false;\
    }\
}

#define DebugBoolFuncErrorReturn(func)   {\
     if(!func){\
        DebugBoolFlag(#func LOCATION); \
        return false;\
    }\
}



bool abc(bool result){

    printf("calling abc\n");
    return result;
}




int main()
{

    // 不return,发生错误的时候打印日志,并附加自定义的log
    bool result = DebugBoolFuncNoReturnWithCustomLog( abc(0), "bool custom log!" );

    printf("%d\n", result);

    // 不return,发生错误的时候打印日志
    result = DebugBoolFuncNoReturn( abc(0) );

    printf("%d\n", result);

    // 当发生错误的时候return,发生错误的时候打印日志,并附加自定义的log
    DebugBoolFuncErrorReturnWithCustomLog(abc(0), "bool custom log!");

    // 当发生错误的时候return,发生错误的时候打印日志
    DebugBoolFuncErrorReturn(abc(0));

    printf("END\n");

    return 0;
}



                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值