1

As the following c code:

#define __xstr(s) __str(s)
#define __str(s) #s

what does #s mean?

zebo zhuang
  • 566
  • 1
  • 5
  • 15
  • 2
    Unless it's part of the implementation, it has undefined behavior. Identifiers starting with two underscores, or with an underscore followed by an uppercase letter, are reserved. – Keith Thompson Apr 27 '15 at 15:58

2 Answers2

2

It is the Stringification operator:

The # operator (known as the "Stringification Operator") converts a token into a string, escaping any quotes or backslashes appropriately.

Example:

#define str(s) #s

str(p = "foo\n";) // outputs "p = \"foo\\n\";"
str(\n)           // outputs "\n"

If you want to stringify the expansion of a macro argument, you have to use two levels of macros:

#define xstr(s) str(s)
#define str(s) #s
#define foo 4

str (foo)  // outputs "foo"
xstr (foo) // outputs "4"

The code in the last sample is very close to the code in the question. Please be aware, as @KeithThompson mentioned, that "identifiers starting with two underscores, or with an underscore followed by an uppercase letter, are reserved".

Community
  • 1
  • 1
AlexD
  • 32,156
  • 3
  • 71
  • 65
0

The macros allows to do stringification, that is convert a macro argument into a string:

__xstr(foo) yields "foo"

__xstr(4) yields "4"

and

#define BLA bar

__xstr(BLA) yields "bar"

You need two levels of macros to achieve this, see here for more info:

https://gcc.gnu.org/onlinedocs/cpp/Stringification.html

ouah
  • 142,963
  • 15
  • 272
  • 331