Home >Backend Development >C++ >How Does Macro Expansion Order Affect Stringification in C and C ?

How Does Macro Expansion Order Affect Stringification in C and C ?

Barbara Streisand
Barbara StreisandOriginal
2024-12-25 17:24:10450browse

How Does Macro Expansion Order Affect Stringification in C and C  ?

Stringification: Understanding the Macro Expansion Process

In the realm of C and C , the term "stringification" refers to the conversion of a macro argument into a string literal. However, the process can be intricate, as demonstrated by the following scenario:

#define foo 4
#define str(s) #s

In this case, str(foo) outputs "foo" because the stringification process (the # operator) is executed before the macro expansion (the #define directive). This ensures that foo remains a macro name and is not substituted with its value.

However, the following code snippet produces a different result:

#define xstr(s) str(s)
#define str(s) #s
#define foo 4

With xstr(foo) called, the output becomes "4." To comprehend this behavior, we must delve into the intricacies of macro expansion.

According to the C and C standards, the macro expansion process entails the following steps:

  1. Identify and process tokens preceded by # or ## (the stringification operator).
  2. Substitute the corresponding macro definitions for any macro arguments.
  3. Replace each function parameter with the result of the macro replacement.
  4. Rescan the code for additional macros.

In the case of xstr(foo):

  1. The xstr macro requires no stringification (step 1).
  2. foo is replaced with its value, 4 (step 2).
  3. Within the str macro, s is replaced with 4, resulting in str(4) (step 3).
  4. str(4) is rescanned, yielding "4" (final step).

The key difference here lies in the step where macro arguments are substituted (step 2). With str(foo) in the first example, step 2 occurs after the stringification has been applied in step 1. Hence, foo is not replaced, and the output remains "foo."

To address this issue, the helper macro xstr is employed. By nesting macros, we can first perform the argument substitution in step 2 and then apply stringification in step 1, ensuring the desired result of "4" is obtained.

The above is the detailed content of How Does Macro Expansion Order Affect Stringification in C and C ?. 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