C 语言预处理器行为
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当实际使用“HYPE”时,就会发生替换。当 #define 语句出现时它不会被扩展。
例如:
所以替换发生在第 5 行,而不是第 1 行。因此你的问题的答案是:一次。
the replacement takes place, when "HYPE" is actually used. it is not expanded when the #define statement occurs.
eg:
so the replacement takes place in line 5, and not in line 1. hence the answer to your question is: once.
#define
的宏调用将被扩展,直到没有更多的术语可以扩展,但它不会递归。例如:假设您说
factorial(2)
。它将扩展为((2) == 0 ? 1 : (2) * Factorial((2)-1))
。请注意,factorial
被扩展,然后TIMES
也被扩展,但是factorial
之后不会再次扩展,因为这将是递归。但是,请注意,嵌套(可以说是一种不同类型的“递归”)实际上在同一表达式中扩展了多次:
A #define
'd macro invocation is expanded until there are no more terms to expand, except it doesn't recurse. For example:Suppose you say
factorial(2)
. It will expand to((2) == 0 ? 1 : (2) * factorial((2)-1))
. Note thatfactorial
is expanded, thenTIMES
is also expanded, butfactorial
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: