What's the exact step of macro expanding?

2020-02-07 01:38发布

问题:

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?

回答1:

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:

#define stringify(x) #x
stringify(__LINE__)

Then, the preprocessor does not expand __LINE__, because it's the argument of the stringizing operator. However, when you do this:

#define stringify1(x) #x
#define stringify(x) stringify1(x)
stringify(__LINE__)

Then, when expanding stringify, the preprocessor expands __LINE__ to the current line number, since x is not used with either the stringizing or token-pasting operators in the definition of stringify. It then expands stringify1, and we get what we wanted.

The relevant language from the C99 standard comes from §6.10.3.1/1:

After the arguments for the invocation of a function-like macro have been identified, argument substitution takes place. A parameter in the replacement list, unless preceded by a # or ## preprocessing token or followed by a ## preprocessing token (see below), is replaced by the corresponding argument after all macros contained therein have been expanded. Before being substituted, each argument’s preprocessing tokens are completely macro replaced as if they formed the rest of the preprocessing file; no other preprocessing tokens are available.

Clauses §6.10.3.2 and 6.10.3.3 go on to define the behavior of the # and ## operators respectively.



标签: c macros