2

Possible Duplicate:
How, exactly, does the double-stringize trick work?

I came across this the other day - can someone tell me how it works?

A simple way to stringize a C preprocessor constant, in all compilers conforming to ANSI C (or any C++ compiler).

Suppose you have a header file containing a constant like #define FIELD1_WIDTH 17. Now you want to build the string "%17s", which tells printf the width of the field. If you're a wimp, you can use a format string "%*d" and pass FIELD1_WIDTH in as the first parameter. But that doesn't solve other problems. You might also want to put an identifier string in your program giving the values of important constants, which strings can find. In other words, you have to be able to translate FIELD1_WIDTH into "17". And because you'll be doing it with some constant surrounding text, you'd like a macro to do it for you.

This is so easy as barely to be worth mentioning. Actually, I lied. It's impossible to guess the horrible hack that does it. Just do this:

#define STR(x)   #x
#define XSTR(x)  STR(x) 

Then using XSTR(FIELD1_WIDTH) yields the string "17". The rôle of XSTR is particularly mysterious.

hint: STR(FIELD1_WIDTH) expands to "FIELD1_WIDTH", which is not what you want...

thanks :)

Community
  • 1
  • 1
horseyguy
  • 29,455
  • 20
  • 103
  • 145
  • 4
    See: http://stackoverflow.com/questions/2751870/how-exactly-does-the-double-stringize-trick-work – bobDevil Oct 18 '10 at 17:12
  • 1
    I don't see anything 'crazy' about it. – Carl Norum Oct 18 '10 at 17:15
  • 1
    This is a very well known technique with all rewrite-based (macro) languages (m4 and LaTeX for example in addition to cpp). You're just forcing argument `x` to be macro substituted before it's stringified. After the first expansion of `XSTR` you have `STR(FIELD1_WIDTH)`. The macro processor then expands `FIELD1_WIDTH` to `17` (because it's required to eagerly expand arguments before the macro call that binds the argument) then finally expands `STR(17)`. – Gene Aug 30 '14 at 02:24

0 Answers0