This doesn’t work as expected:
#define stringify(x) #x
printf("Error at line " stringify(__LINE__));
This works:
#define stringify1(x) #x
#define stringify(x) stringify1(x)
printf("Error at line " stringify(__LINE__));
What’s the priority that preprocess uses to expand such macros?
When expanding a macro, the preprocessor expands the macro’s arguments only if those arguments are not subjected to the stringizing (
#) or token-pasting (##) operators. So, if you have this:Then, the preprocessor does not expand
__LINE__, because it’s the argument of the stringizing operator. However, when you do this:Then, when expanding
stringify, the preprocessor expands__LINE__to the current line number, sincexis not used with either the stringizing or token-pasting operators in the definition ofstringify. It then expandsstringify1, and we get what we wanted.The relevant language from the C99 standard comes from §6.10.3.1/1:
Clauses §6.10.3.2 and 6.10.3.3 go on to define the behavior of the
#and##operators respectively.