在C语言中,
##运算符(称为
[size=16.002px]标记拼接运算符)用于宏定义中将两个标记(token)拼接成一个新的标记。它在预处理阶段处理,常用于动态生成变量名、函数名或类型名,以提高代码的复用性和减少冗余。
1、生成函数或类型名:
- #define DEFINE_MAX(type)
- type type##_max(type a, type b) {
- return a > b ? a : b;
- }
- DEFINE_MAX(int) // 生成 int_max 函数
- DEFINE_MAX(float) // 生成 float_max 函数
2、结合字符串化(
[size=0.875em]#运算符)生成日志函数:
- #define DEFINE_LOG(module)
- void log_##module(const char* msg) {
- printf("[%s] %sn", #module, msg);
- }
- DEFINE_LOG(network) // 生成 log_network 函数
- DEFINE_LOG(file) // 生成 log_file 函数