字串化 - 它是如何工作的? [英] Stringification - how does it work?

查看:144
本文介绍了字串化 - 它是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道:

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

STR(富)写出:foo的,因为字符串化执行第一个文本扩展,但这:

with str(foo) writes out: "foo", because stringify is executed first of text expansion, but this:

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

XSTR(富)写出:4

为什么呢?什么是参与这个过程的步骤是什么?

Why? What are the steps involved in the process?

推荐答案

宏扩展的相关步骤是(每Ç2011 [n1570] 6.10.3.1和C ++ 1998年16.3.1):

The relevant steps of macro expansion are (per C 2011 [n1570] 6.10.3.1 and C++ 1998 16.3.1):


  1. 标记过程是由 ##
  2. pceded $ P $
  3. 应用宏替换每个参数。

  4. 与上面的宏替换相应的结果替换每个参数。

  5. 重新扫描多个宏。

因此​​,随着 XSTR(富),我们有:

Thus, with xstr(foo), we have:


  1. 替换文本, STR(S),不包含 ## ,所以什么也不会发生。

  2. 参数替换 4 ,所以这是因为如果 XSTR( 4)已被使用。

  3. 在替换文本 STR(S),参数取值替换 4 ,生产 STR(4)

  4. STR(4)重新扫描。 (由此产生的步骤产生4

  1. The replacement text, str(s), contains no # or ##, so nothing happens.
  2. The argument foo is replaced with 4, so it is as if xstr(4) had been used.
  3. In the replacement text str(s), the parameter s is replaced with 4, producing str(4).
  4. str(4) is rescanned. (The resulting steps produce "4".)

请注意,与 STR(富)问题是第2步,将取代 4 ,自带的步骤1,从而改变参数之后的字符串。在步骤1中,还是;它并没有被替换 4 ,所以结果是foo的

Note that the problem with str(foo) is that step 2, which would replace foo with 4, comes after step 1, which changes the argument to a string. In step 1, foo is still foo; it has not been replaced with 4, so the result is "foo".

这就是为什么使用辅助宏。它使我们能够获得一个第2步进行,然后用另一个宏来执行步骤1。

This is why a helper macro is used. It allows us to get a step 2 performed, then use another macro to perform step 1.

这篇关于字串化 - 它是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆