宏评估顺序 [英] Macro evaluation order
问题描述
可能重复:结果
#和##中的宏
块引用>为什么第二个printf的输出为f(1,2)是什么在宏评估顺序?
的#include<&stdio.h中GT;
的#define F(A,B)一个## b
的#define克(一)#a的
的#define小时(一)克(一)
诠释的main()
{
的printf(%S \\ n,H(F(1,2)));
的printf(%S \\ N,G(F(1,2)));
返回0;
}
输出12
F(1,2)
解决方案从<一个href=\"http://gcc.gnu.org/onlinedocs/cpp/Argument-$p$pscan.html#Argument-$p$pscan\">http://gcc.gnu.org/onlinedocs/cpp/Argument-$p$pscan.html#Argument-$p$pscan
宏参数是完全宏扩展它们代入宏体之前,除非它们字符串化或与其他标记粘贴。取代后,整个宏体,包括被取代的参数,再次扫描为要展开的宏。其结果是,参数扫描两次在他们扩大宏调用。
块引用>含义:
- ˚F会将其参数,所以它的参数没有展开
- H不字符串化或连接它的参数,因此它的参数扩展。
- 先按g stringifies它的参数,所以它的参数没有展开
H(F(1,2)) - GT;克(12) - &GT; 12
克(F(1,2)) - GT; F(1,2)
Possible Duplicate:
# and ## in macroswhy the output of second printf is f(1,2) what is the order in which macro is evaluated?
#include <stdio.h> #define f(a,b) a##b #define g(a) #a #define h(a) g(a) int main() { printf("%s\n",h(f(1,2))); printf("%s\n",g(f(1,2))); return 0; } output 12 f(1,2)
解决方案From http://gcc.gnu.org/onlinedocs/cpp/Argument-Prescan.html#Argument-Prescan
Macro arguments are completely macro-expanded before they are substituted into a macro body, unless they are stringified or pasted with other tokens. After substitution, the entire macro body, including the substituted arguments, is scanned again for macros to be expanded. The result is that the arguments are scanned twice to expand macro calls in them.
Meaning:
- f concatenates its argument and so its argument is not expanded
- h does not stringify or concatenate its argument and so its argument is expanded.
- g stringifies its argument, and so its argument is not expanded
h(f(1,2)) -> g(12) -> "12"
g(f(1,2)) -> "f(1,2)"
这篇关于宏评估顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!