2

Possible Duplicate:
Stringification of a macro value

I want to write a C macro that takes a "sequence of characters" (for example, #define macro(sequence)) and return the quoted string "sequence", so the macro should create "\"sequence\"". I know I can do #sequence but this just returns "sequence" which is not what I'm looking for... I must say that "sequence" is another macro, so I can't write it as it is in this macro since it gets "non literally" replaced. Any ideas?

Community
  • 1
  • 1
user732274
  • 1,069
  • 1
  • 12
  • 28
  • 1
    If you have `#define sequence abc`, do you expect `macro(sequence)` to give you `"\"sequence\""` or `"\"abc\""`? – interjay Dec 06 '12 at 10:16

3 Answers3

3
#include <stdio.h>

#define QUOTE(seq) "\""#seq"\""

int main(void)
{
    printf("%s\n", QUOTE(sequence));
    return 0;
}
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
2

Use #sequence but add the quotes before and after:

#define macro(sequence) "\"" #sequence "\""

The string literals will be concatenated giving you the result you want.

For example:

#define hello abc
printf("%s\n", macro(hello));

Will print "hello" (including the quotes).

interjay
  • 107,303
  • 21
  • 270
  • 254
  • I can't get it to work... I wrote this macro: #define disableMacro(M) _Pragma("push_macro(\"" #M "\")") – user732274 Dec 06 '12 at 10:03
  • @user732274: I don't know how `_Pragma` works, but this approach works fine with `printf`: http://ideone.com/BdW4Gi – interjay Dec 06 '12 at 10:18
1

You need one macro to expand the argument and another to add the quotes. Call the latter macro twice to add quotes around the quotes. Escaping is handled automatically in such a case.

#define stringify_literal( x ) # x
#define stringify_expanded( x ) stringify_literal( x )
#define stringify_with_quotes( x ) stringify_expanded( stringify_expanded( x ) )
Potatoswatter
  • 134,909
  • 25
  • 265
  • 421