Home > Backend Development > C++ > Why Does `xstr(foo)` Output '4' While `str(foo)` Outputs 'foo' in C-like Macro Expansion?

Why Does `xstr(foo)` Output '4' While `str(foo)` Outputs 'foo' in C-like Macro Expansion?

Linda Hamilton
Release: 2024-12-28 14:30:11
Original
256 people have browsed it

Why Does `xstr(foo)` Output

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
Copy after login

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)
Copy after login

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:

  1. Preprocess: Tokens preceded by # or ## are processed.
  2. Argument Replacement: Macros are applied to each argument.
  3. Parameter Substitution: Parameters are replaced with the corresponding macro results.
  4. Rescanning: The code is rescanned for further macro expansion.

Applying the Steps to xstr(foo)

  1. Preprocess: No applicable tokens.
  2. Argument Replacement: foo is replaced with 4.
  3. Parameter Substitution: In str(s), s is replaced with 4, producing str(4).
  4. Rescanning: str(4) is rescanned, resulting in the output "4".

Why str(foo) Outputs "foo"

In contrast to xstr(foo), str(foo) yields "foo" because:

  • Preprocess: No stringification tokens present.
  • Argument Replacement: None applicable.
  • Parameter Substitution: #foo remains unchanged because foo hasn't been replaced with 4.
  • Rescanning: #foo is not rescanned, producing "foo".

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template