正确的 C 预处理器宏无操作 [英] Proper C preprocessor macro no-op

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

问题描述

对于调试日志,我经常看到并使用类似的东西

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 被替换为

but in a number of places, I have seen the second #define replaced with

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

特别是this answer,以及对同一问题的其他答案表明问题可能出现在

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.

nothingdo {} while (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 #define 宏解释了为什么您需要不同形式的无操作.你想让编译器解析调试打印代码,即使你不使用它,这样错误就不会蔓延.

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 预处理器宏无操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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