【C/C++】宏定义中的#和##

C和C++中的宏(Macro)属于编译器预处理的范畴。

单井号# 运算符

单井号#(字符串化运算符)用于将 宏参数变量名 转换为 字符串(Stringfication)。

下面是一个示例:

#include <stdio.h>

#define PRINT_VARIABLE(x)  printf(#x " = %d\n", x)

int main() {
    
    
    int num = 10;
    PRINT_VARIABLE(num);
    return 0;
}

在上面的例子中,#x 会将 宏PRINT_VARIABLE接收的参数x 转化为字符串常量。此例中PRINT_VARIABLE接收的参数变量名是num,因此#x就等价于"num"其在输出时会显示:

num = 10

双井号## 运算符

双井号##(连接运算符,concatenator)用于将两个标记(Token)连接在一起
例如:

#include <stdio.h>
#define CONCAT(x, y)  x##y

int main() {
    
    
    int result = CONCAT(3, 5);
    printf("Result: %d\n", result);
    return 0;
}

输出结果为:

Result: 35

再例如:

#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://www.cnblogs.com/lixiaofei1987/p/3171439.html

猜你喜欢

转载自blog.csdn.net/qq_39441603/article/details/133847122