Stringizing macro arguments in a multi-level macro call
-
12-03-2021 - |
Pergunta
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.)
Solução
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
#define SHOW_EXPR_(STR, EXP) printf (STR "=%d\n", EXP)
#define SHOW_EXPR(...) SHOW_EXPR_(#__VA_ARGS__, (__VA_ARGS__))
#define MY_SHOW_EXPR(...) SHOW_EXPR_("Look ma, " #__VA_ARGS__, (__VA_ARGS__))
which as an extra feature even would work if the expression contains a comma.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow