문제

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.)

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top