Convert a preprocessor token to a string

davenpcj picture davenpcj · Oct 27, 2008 · Viewed 77.2k times · Source

I'm looking for a way to convert a preprocessor token to a string.

Specifically, I've somewhere got:

#define MAX_LEN 16

and I want to use it to prevent buffer overrun:

char val[MAX_LEN+1]; // room for \0
sscanf(buf, "%"MAX_LEN"s", val);

I'm open to other ways to accomplish the same thing, but standard library only.

Answer

Dan picture Dan · Oct 27, 2008

see http://www.decompile.com/cpp/faq/file_and_line_error_string.htm specifically:

#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define AT __FILE__ ":" TOSTRING(__LINE__)

so your problem can be solved by doing sscanf(buf, "%" TOSTRING(MAX_LEN) "s", val);