C preprocessor: stringize macro and identity macro

风格不统一 提交于 2019-12-18 03:39:06

问题


I want to know the reason behind the output of this code. I couldn't come up with an answer.

#define f(a,b) a##b
#define g(a) #a
#define h(a) g(a)
void main()
{
   printf("%s %s",h(f(1,2)),g(f(1,2)));
}

PS: output is 12 f(1,2). I thought it was 12 12 or f(1,2) f(1,2).


回答1:


h(f(1,2))

f(1,2) is substituted for a. a is not the subject of a # or ## operator so it's expanded to 12. Now you have g(12) which expands to "12".

g(f(1,2))

f(1,2) is substituted for a. The # operator applied to a prevents macro expansion, so the result is literally "f(1,2)".




回答2:


Just do the replacements.

h(f(1, 2)) -> g(12) -> "12"

g(f(1,2)) -> "f(1, 2)"

You should also see here.



来源:https://stackoverflow.com/questions/11610111/c-preprocessor-stringize-macro-and-identity-macro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!