宏定义中 # 和 ## 的作用

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

双井号:就是用于连接

#include <stdio.h>
#define COMMAND(NAME) {#NAME,NAME##_command}
#define PRINT(NAME) printf("token"#NAME"=%d\n", token##NAME)
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);
};  

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()中通过函数指针来调用函数

 

posted @ 2018-01-15 17:43  大漠垂杨  阅读(2172)  评论(0编辑  收藏  举报