C语言中的“#”和“##”

参考stackoverflow上的这篇帖子

#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;
}

运行结果如下:

12
f(1,2)

#a会创建一个字符串:"a"a##b会创建一个新的tokenab。关于macro的处理,参考下列解释:

An occurrence of a parameter in a function-like macro, unless it is the operand of # or ##, is expanded before substituting it and rescanning the whole for further expansion. Because g’s parameter is the operand of #, the argument is not expanded but instead immediately stringified (“f(1,2)”). Because h’s parameter is not the operand of # nor ##, the argument is first expanded (12), then substituted (g(12)), then rescanning and further expansion occurs (“12”).

总结一下,对于function-like macro的参数,如果是#或者##的操作数,则会马上扩展为相应的字符串;否则会先扩展,再替换,循环此操作,直到完成。因此对于g(f(1,2)),会马上替换成"f(1,2)"这个字符串。而对于h(f(1,2)),由于其参数不是#..或者..#..,所以会先把f(1,2)扩展成12,然后替换变成g(12),最后变成"12"

发表评论

邮箱地址不会被公开。 必填项已用*标注

This site uses Akismet to reduce spam. Learn how your comment data is processed.