gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 02:21:32 26 4
gpt4 key购买 nike

我在 C: From Theory to Practice 一书中偶然发现了这一行,第 436 页:

“预处理器将嵌套宏从内部扩展到外部。”

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

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

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

我很困惑。

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

最佳答案

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

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

例如:

#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 行中,我使用花括号 {} 来标记嵌套宏的扩展。括号[]中的数字为展开时的嵌套层级。下一个括号显示当前展开的宏的名称。

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

关于c++ - 嵌套宏的扩展,从内到外?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31307503/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com