字串化 - 它是如何工作的? [英] Stringification - how does it work?
问题描述
我知道:
#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):
- 标记过程是由
#
或##
。 pceded $ P $ - 应用宏替换每个参数。
- 与上面的宏替换相应的结果替换每个参数。
- 重新扫描多个宏。
因此,随着 XSTR(富)
,我们有:
Thus, with xstr(foo)
, we have:
- 替换文本,
STR(S)
,不包含#
或##
,所以什么也不会发生。 - 参数
富
替换4
,所以这是因为如果XSTR( 4)
已被使用。 - 在替换文本
STR(S)
,参数取值
替换4
,生产STR(4)
。 -
STR(4)
重新扫描。 (由此产生的步骤产生4
)
- The replacement text,
str(s)
, contains no#
or##
, so nothing happens. - The argument
foo
is replaced with4
, so it is as ifxstr(4)
had been used. - In the replacement text
str(s)
, the parameters
is replaced with4
, producingstr(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屋!