嵌套宏的扩展,从内到外?

Expansion of nested macros, from the inner to the outer?

我在 C: From Theory to Practice, p.436:

一书中偶然发现了这一行

"The preprocessor expands the nested macros from the inner to the outer."

但我认为它是从外部扩展到内部的。我一直都错了吗?

例如,您有宏 #define FUNC(x,y) x+y#define PARA 3,4,但您不能使用 FUNC(PARA)。我认为 FUNCPARA 之前得到扩展。

类似地,当您像 #define str(s) #s 那样进行字符串化时,使用 str(__LINE__) 会导致 "__LINE__"

我很困惑。

如果嵌套宏是从内向外展开的,那么这2个例子怎么理解?

答案是这些不是嵌套宏,而是参数中的宏。可能会有一些混淆,因为一些消息来源仍然将它们称为 "nested" 宏。不过确实,参数是后面展开的

嵌套宏是在另一个宏的替换列表中的宏。这些在包含它们的宏被展开之前被展开。

参见示例:

#define foo "foo" bar baz
#define bar "bar" baz foo
#define baz "baz" foo bar

foo
bar
baz

导致以下扩展:

"foo" "bar" "baz" foo bar foo "baz" foo "bar" baz foo
"bar" "baz" "foo" bar baz bar "foo" bar "baz" foo bar
"baz" "foo" "bar" baz foo baz "bar" baz "foo" bar baz

发生了什么(只详细解释了第一行)?

1.  [1][foo] bar is found -> expand this first
2.  [2][bar] baz is found -> expand this first
3.  [3][baz] foo is found -> already in "foo" expansion, ignore
4.  [3][baz] bar is found -> already in "bar" expansion, ignore
5.  [3][baz] baz expands to ["baz" foo bar]
6.  [2][bar] foo is found -> already in "foo" expansion, ignore
7.  [2][bar] bar expands to ["bar" "baz" foo bar foo] <- note baz was expanded before bar
8.  [1][foo] baz is found -> expand this first
9.  [2][baz] foo is found -> already in "foo" expansion, ignore
10. [2][baz] bar is found -> expand this first
11. [3][bar] baz is found -> already in "baz" expansion, ignore
12. [3][bar] foo is found -> already in "foo" expansion, ignore
13. [3][bar] bar expands to ["bar" baz foo]
14. [2][baz] baz expands to ["baz" foo "bar" baz foo] <- note bar was expanded first
15. [1][foo] foo expands to ["foo" { "bar" "baz" foo bar foo } { "baz" foo "bar" baz foo } ]

注意:在第15行,我用大括号{}来标记嵌套宏的扩展。括号[]中的数字为展开时的嵌套层数。下一个括号显示当前展开的宏的名称。

在下降到最内层的嵌套宏时,预处理器知道它当前尝试扩展哪些宏,并且不会尝试嵌套扩展它们,以避免递归扩展。