转:C语言宏定义时#(井号)和##(双井号)的用法

时间:2021-10-11 08:57:30

转自:http://www.cnblogs.com/welkinwalker/archive/2012/03/30/2424844.html#2678295

#在英语里面叫做 pound

在C语言的宏定义中,一个#表示字符串化;两个#代表连接。

#include <iostream>
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=;
PRINT();
struct command commands[] = {
COMMAND(quit),
COMMAND(help),
};
commands[].function();
}

得到的结果是:

token9=9
I am quit command