C 语言预处理器行为

发布于 2024-09-04 03:47:21 字数 297 浏览 3 评论 0原文

C语言中有不同类型的宏,嵌套宏就是其中之一。

考虑一个带有以下宏的程序

#define HYPE(x,y) (SQUR(x)+SQUR(y))
#define SQUR(x)   (x*x)

使用它我们可以成功编译以获得结果。

众所周知,C 预处理器用替换字符串替换所有出现的标识符。考虑到上面的例子,我想知道C预处理器遍历程序多少次以用替换值替换宏。我认为这不可能一次性完成。

There are different kind of macros in the C language, nested macro is one of them.

Considering a program with the following macro

#define HYPE(x,y) (SQUR(x)+SQUR(y))
#define SQUR(x)   (x*x)

Using this we can successfully compile to get the result.

As we all know the C preprocessor replaces all the occurrence of the identifiers with the replacement-string. Considering the above example I would like to know how many times the C preprocessor traverses the program to replace the macro with the replacement values. I assume it cannot be done in one go.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

挽心 2024-09-11 03:47:22

当实际使用“HYPE”时,就会发生替换。当 #define 语句出现时它不会被扩展。

例如:

1 #define FOO 1
2
3 void foo() {
4    printf("%d\n", FOO);
5 }

所以替换发生在第 5 行,而不是第 1 行。因此你的问题的答案是:一次。

the replacement takes place, when "HYPE" is actually used. it is not expanded when the #define statement occurs.

eg:

1 #define FOO 1
2
3 void foo() {
4    printf("%d\n", FOO);
5 }

so the replacement takes place in line 5, and not in line 1. hence the answer to your question is: once.

我是有多爱你 2024-09-11 03:47:22

#define 的宏调用将被扩展,直到没有更多的术语可以扩展,但它不会递归。例如:

#define TIMES        *
#define factorial(n) ((n) == 0 ? 1 : (n) TIMES factorial((n)-1))
    // Doesn't actually work, don't use.

假设您说factorial(2)。它将扩展为 ((2) == 0 ? 1 : (2) * Factorial((2)-1))。请注意,factorial 被扩展,然后 TIMES 也被扩展,但是 factorial 之后不会再次扩展,因为这将是递归。

但是,请注意,嵌套(可以说是一种不同类型的“递归”)实际上在同一表达式中扩展了多次:

#define ADD(a,b)     ((a)+(b))
....
ADD(ADD(1,2),ADD(3,4)) // expands to ((((1)+(2)))+(((3)+(4))))

A #define'd macro invocation is expanded until there are no more terms to expand, except it doesn't recurse. For example:

#define TIMES        *
#define factorial(n) ((n) == 0 ? 1 : (n) TIMES factorial((n)-1))
    // Doesn't actually work, don't use.

Suppose you say factorial(2). It will expand to ((2) == 0 ? 1 : (2) * factorial((2)-1)). Note that factorial is expanded, then TIMES is also expanded, but factorial isn't expanded again afterwards, as that would be recursion.

However, note that nesting (arguably a different type of "recursion") is in fact expanded multiple times in the same expression:

#define ADD(a,b)     ((a)+(b))
....
ADD(ADD(1,2),ADD(3,4)) // expands to ((((1)+(2)))+(((3)+(4))))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文