宏定义中 # 和 ## 的作用

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

双井号:就是用于连接

#include <stdio.h>
#define COMMAND(NAME) {#NAME,NAME##_command}
#define PRINT(NAME) printf("token"#NAME"=%d
", token##NAME)
void quit_command(){
    printf("I am quit command
");
}   
void help_command(){
    printf("I am help command
");
}   
struct command
{
    char * name;
    void (*function) (void);
};  

int main(){
    int token9=9;
    PRINT(9);
    struct command commands[] = {
        COMMAND(quit),
        COMMAND(help),
    };  
    commands[0].function();
	return 0;
}

执行结果:

token9=9
I am quit command

解释一下,COMMAND宏定义是有{}的,第一个#NAME,就是赋值给结构体command的char *name,第二个 NAME##_command,用来拼出函数名,赋值给结构体中的函数指针,之后在commands[0].function()中通过函数指针来调用函数

原文地址:https://www.cnblogs.com/yorkyang/p/8289116.html