C语言宏定义##连接符和#符的使用

    xiaoxiao2021-03-25  86

    关于#和##

    一  、#

        在C语言的宏中,#的功能是将其后面的宏参数进行字符串化操作(Stringfication),简单说就是在对它所引用的宏变量通过替换后在其左右各加上一个双引号。

    在一个预处理器宏中的参数前面使用一个#,预处理器会把这个参数转换为一个字符数组。(原文:When you put a # before an argument in a preprocessor 

    macro, the preprocessor turns that argument into a character array. This, 

    combined with the fact that character arrays with no intervening punctuation 

    are concatenated into a single character array, allows you to make a very 

    convenient macro for printing the values of variables during debugging

    #include "iostream"

    using namespace std;

    #define P(A) cout<<#A<<": "<<(A)<<endl;

    int main()

    {

    int a=1,b=2;

    P(a);

    P(b);

    P(a+b);

    return 1;

    }

    #A输出了变量名,而A仅仅是输出了这是值。将会有以下结果

    a:1

    b:2

    c:3

    二、##

    n个##符号连接 n+1个Token,这个特性也是#符号所不具备的。比如:

    #define LINK_MULTIPLE(a,b,c,d) a##_##b##_##c##_##d typedef struct _record_type LINK_MULTIPLE(name,company,position,salary); // 这里这个语句将展开为: // typedef struct _record_type name_company_position_salary;

    转载请注明原文地址: https://ju.6miu.com/read-23695.html

    最新回复(0)