user3568006
user3568006

Reputation: 35

force macro evaluation in C

I want to change an extensively used C macro that today takes a string as argument to just take the name of the string without quotation marks. I will then stringify the name in the macro using #. I want the change to be easy to adapt to for the user (removal of the quotation marks in the easiest case).

Macro example, change from:

#define MY_MACRO(x) (foo(x))

to

#define MY_MACRO_NEW(x) (foo(#x))

The problem is that sometimes a macro is used as argument instead of a string directly, like this:

#define BAR "bar"
MY_MACRO(BAR);

if the quotation marks are removed and the macro is changed:

#define BAR bar
MY_MACRO_NEW(BAR);

BAR will not be evaluated since MY_MACRO_NEW stringify using #, the resulting string will therefore be BAR rather than the desired bar.

Is this a way to force evaluation of BAR before it is being evaluated by MY_MACRO_NEW? Something like:

#define BAR bar
MY_MACRO_NEW(MACRO_EVAL(BAR));

Thanks!

Upvotes: 0

Views: 689

Answers (1)

Matheus Rossi Saciotto
Matheus Rossi Saciotto

Reputation: 1131

You can use a macro that does nothing to pass a cycle.

#include <stdio.h>

#define MY_MACRO_NEW(x) MY_MACRO_NEW_(x)
#define MY_MACRO_NEW_(x) (foo(#x))

void foo(const char *msg) {
    printf("%s\n", msg);
}

#define BAR bar

int main() {
    MY_MACRO_NEW(BAR);
    return 0;
}

Outputs:

bar

If your evaluation takes more than one expansion cycle you will need more dummy macros.

Upvotes: 2

Related Questions