Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stringizing macro arguments in a multi-level macro call

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

like image 437
n. 1.8e9-where's-my-share m. Avatar asked Oct 21 '25 04:10

n. 1.8e9-where's-my-share m.


1 Answers

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.

like image 68
Jens Gustedt Avatar answered Oct 22 '25 20:10

Jens Gustedt