问题描述
有关调试日志记录,我经常看到并使用类似
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?
推荐答案
请参阅了解为什么需要不同形式的无操作的解释。你想拥有,当你不使用它的编译器解析调试印刷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宏观空操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!