Home >Backend Development >C++ >Why Does Stringification Produce 'foo' in One Case and '4' in Another?

Why Does Stringification Produce 'foo' in One Case and '4' in Another?

Linda Hamilton
Linda HamiltonOriginal
2024-12-24 04:20:10911browse

Why Does Stringification Produce

Stringification Unraveled: A Step-by-Step Explanation

Stringification is a powerful macro technique that converts a given token into a string literal. To understand its intricacies, let's examine the following scenario:

define foo 4

define str(s) #s

With str(foo), the expected output is "foo" because stringification is believed to occur before text expansion. However, in the second example:

define xstr(s) str(s)

define str(s) #s

define foo 4

The output of xstr(foo) becomes "4." To unravel this discrepancy, we delve into the specific steps involved in macro expansion:

  1. Preprocessing Directives: Macros beginning with # or ## are processed first.
  2. Argument Substitution: Arguments within macros are replaced with corresponding values.
  3. Parameter Substitution: Parameters are replaced with their respective argument values.
  4. Rescanning for Macros: The resulting text is rescanned for additional macros.

Applying these steps to xstr(foo):

  1. Nothing happens as str(s) contains no # or ##.
  2. foo is replaced with 4, resulting in xstr(4).
  3. Within str(s), s is replaced with 4, generating str(4).
  4. str(4) is rescanned, producing the final output of "4."

Now, let's examine str(foo):

  1. The argument foo is still foo (not replaced with 4).
  2. The replacement text, #s, produces "foo."

The crux of the issue lies in the sequence of execution. In step 1, when str(foo) is evaluated, foo has not yet been replaced with 4. Therefore, the stringification step results in "foo."

Hence, the use of a helper macro like xstr allows for separate execution of steps 2 and 1, ultimately providing the desired stringification behavior.

The above is the detailed content of Why Does Stringification Produce 'foo' in One Case and '4' in Another?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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