关于c语言宏定义中的单#(井号)和双#(井号)

转载自# 三更_雨

看了这篇文章后了解了,但是文章中的例子比较特别,我在这里加个注释好了。

http://www.cnblogs.com/welkinwalker/archive/2012/03/30/2424844.html

单井号就是将后面的 宏参数 进行字符串操作,就是将后面的参数用双引号引起来

双井号就是用于连接。

比如文章中的例子:

#define PRINT(NAME) printf("token"#NAME"=%d\n", token##NAME)

调用时候使用: PRINT(9);
宏展开即为:

printf("token"#9"=%d\n",token##9);

"#9"即为"9",token##9即为: token9
整个为:

printf("token""9""=%d\n",token9);

之前定义过token9为9,所以就是输出 token9=9;

解释到这里应该就明白单#和双#怎么用了。附上代码,还是摘自上面的连接。

void quit_command(){
    printf("I am quit command\n");
} void help_command(){
    printf("I am help command\n");
} struct command
{ char * name; void (*function) (void);
}; #define COMMAND(NAME) {#NAME,NAME##_command}
#define PRINT(NAME) printf("token"#NAME"=%d\n", token##NAME) main(){ int token9=9;
    PRINT(9); struct command commands[] = {
        COMMAND(quit),
        COMMAND(help),
    };  
    commands[0].function();
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。