syvex
syvex

Reputation: 7766

Is there a way to remove quotes in a C macro?

Suppose I want to un-stringify the macro argument which should transform "text" to text.

#define UN_STRINGIFY(x) /* some macro magic here */

Now calling this macro will remove "" from its argument

UN_STRINGIFY("text") // results in ----> text

This would be the opposite of macro stringification:

#define STRINGIFY(x) #x

Is this possible, or am I playing with macro evilness?

Upvotes: 19

Views: 18138

Answers (2)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 123431

I came to this question already several times and still I can't get it into my head. Consider this example:

#define FOO(x) x

// FOO( destringify("string x;"))   // no way

auto f = "string x;";
FOO(string x;)                      // hm whats the problem?

To me it seems obvious that it should be possible to remove the quotes. I mean string x; is nothing else than "string x;" without the quotes. The thing is: It is just not possible. I don't think there is a technical reason for that, and one can only speculate why there is no method to do it.

However, I managed to convince myself by remembering that basically all the preprocessor does is textual replacement, hence why would you want to "de-textify" something when on the level of the preprocessor anyhow everything is just text. Just do it the other way around. When I change the above example to this:

#define FOO(x) x
#define STR(x) STRSTR(x)
#define STRSTR(x) #x

#define STR_X string x;

auto f = STR(STR_X)
FOO(STR_X)

Then there is no need to de-stringify. And if you ever find yourself in the situation that you want to de-stringify a string via a macro that is not known before compile-time, then your are on the wrong track anyhow ;).

Upvotes: 4

ThiefMaster
ThiefMaster

Reputation: 318738

It's not possible. And that's probably a good thing: If you pass a string you assume you can put pretty much everything in it. Un-stringifying it would suddenly result in the compiler actually caring about the contents of that string.

Upvotes: 12

Related Questions