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)
yields the string "17
". The rôle of
is particularly mysterious.
STR(FIELD1_WIDTH) expands to "FIELD1_WIDTH", which is not what you want...