在多级宏调用中字符串化宏参数
我有一个像这样的宏:
#define SHOW_EXPR(x) printf ("%s=%d\n", #x, (x))
它有效:
#define FOO 123
int BAR = 456;
SHOW_EXPR(FOO+BAR);
这将按预期打印 FOO+BAR=579
。
现在我试图定义一个调用 SHOW_EXPR 的宏:
#define MY_SHOW_EXPR(x) (printf ("Look ma, "), SHOW_EXPR(x))
MY_SHOW_EXPR(FOO+BAR)
这将打印 Look ma, 123+BAR=579
,这也是预期的,但这不是我想要的。
是否可以定义 MY_SHOW_EXPR 以使其执行正确的操作?
(实际的宏比这里显示的要复杂一些。我知道宏是邪恶的。)
I have a macro like this:
#define SHOW_EXPR(x) printf ("%s=%d\n", #x, (x))
It works:
#define FOO 123
int BAR = 456;
SHOW_EXPR(FOO+BAR);
This prints FOO+BAR=579
as expected.
Now I'm trying to define a macro that calls SHOW_EXPR:
#define MY_SHOW_EXPR(x) (printf ("Look ma, "), SHOW_EXPR(x))
MY_SHOW_EXPR(FOO+BAR)
This prints Look ma, 123+BAR=579
, which is also expected, but this is not what I want.
Is it possible to define MY_SHOW_EXPR such that it does the right thing?
(Actual macros are a bit more complicated than shown here. I know that macros are evil.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
宏就像菜刀,你可以用它们做坏事,但它们本身并不是邪恶的。
我会做这样的事情,
如果表达式包含逗号,它作为一个额外的功能甚至可以工作。
Macros are like kitchen knifes, you can do evil things with them but they are not evil as such.
I'd do something like this
which as an extra feature even would work if the expression contains a comma.