宏定义中 # 和 ## 的作用

it2022-05-08  6

 

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

双井号:就是用于连接

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

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

}

执行结果:

1

2

token9=9

I am quit command

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


最新回复(0)