恰当的C preprocessor宏观空操作 [英] Proper C preprocessor macro no-op

查看:96
本文介绍了恰当的C preprocessor宏观空操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关调试日志记录,我经常看到并使用类似

For debug logging, I have often seen and used something like

#ifdef DEBUG
    #define DLOG(fmt, args...) printf("%s:%d "fmt,__FILE__,__LINE__,args)
#else
    #define DLOG(fmt, args...)
#endif

但在一些地方,我看到了第二个的#define

#define DLOG(fmt, args...) do {} while (0)

在特定的,有这个答案和上的这对方的回答以同样的问题表明,这个问题将在一个类似的情况。

In particular, there's this answer, and the comment on this other answer to the same question suggests that the problem would be in a situation like

if (condition)
    DLOG("foo");

虽然我的快速测试表明,本身就行所产生的分号将作为条件内无操作的语句。

though my quick test suggests that the resulting semicolon on the line by itself will serve as the no-op statement inside the conditional.

是一个或其他的的任何做{}而(0)更好?如果是这样,为什么?有没有别的东西,甚至更好?

Is one or the other of nothing and do {} while (0) better? If so, why? Is there something else that's even better?

推荐答案

请参阅C #定义宏调试印刷了解为什么需要不同形式的无操作的解释。你想拥有,当你不使用它的编译器解析调试印刷code即便这样的错误不蠕变

See C #define macro for debug printing for an explanation of why you want a different form of no-op. You want to have the compiler parse the debug printing code even when you aren't using it so that errors do not creep in.

这篇关于恰当的C preprocessor宏观空操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆