Understanding Stringification: The Key Steps of Macro Expansion
The concept of stringification in C-like languages allows you to convert expressions into strings. Understanding the steps involved in this process is crucial for effective macro usage.
The Problem: Difference in Output
Consider the following macro definition:
#define foo 4 #define str(s) #s
When you use str(foo) in your code, it will output "foo" because stringification (step 1) is performed before text expansion (step 2).
However, if you define an additional macro:
#define xstr(s) str(s)
And use xstr(foo), the output will surprisingly be "4". This difference requires an exploration of the stringification process.
Steps of Macro Expansion
The process of macro expansion involves several steps, as per C and C standards:
Applying the Steps to xstr(foo)
Why str(foo) Outputs "foo"
In contrast to xstr(foo), str(foo) yields "foo" because:
Therefore, the use of a helper macro like xstr ensures that text expansion (step 2) is performed before stringification (step 1), allowing for correct string conversions.
The above is the detailed content of Why Does `xstr(foo)` Output '4' While `str(foo)` Outputs 'foo' in C-like Macro Expansion?. For more information, please follow other related articles on the PHP Chinese website!