Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
436 views
in Technique[技术] by (71.8m points)

c - What's the exact step of macro expanding?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...