zoukankan      html  css  js  c++  java
  • 关于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;

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

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

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

  • 相关阅读:
    正则判断是否为纯数值
    前后端加密解密crypto.js
    小程序使用iconfont字体图标
    LeetCode-Combination Sum II
    LeetCode-Combination Sum
    Google 2013 campus test-R1
    Google Codejam
    LeetCode-Count and Say
    LeetCode-Binary Tree Level Order Traversal II
    LeetCode-Binary Tree Level Order Traversal
  • 原文地址:https://www.cnblogs.com/cyttina/p/3072969.html
Copyright © 2011-2022 走看看