#运算符:利用宏参数创建字符串
- # 运算符用于在预处理期将宏参数转换为字符串
- # 的转换作用是在预处理期完成的,因此只在宏定义中有效
- 编译器不知道 # 的转换作用
- 用法
#define STRING(x) #x
printf("%s\n", STRING(Hello World!));
示例代码:#运算符的基本用法
#include <stdio.h>
#define CALL(f, p) (printf("Call function %s\n", #f), f(p))
int square(int n)
{
return n * n;
}
int func(int x)
{
return x;
}
int main()
{
int result = 0;
result = CALL(square, 4);
printf("result = %d\n", result);
result = CALL(func, 10);
printf("result = %d\n", result);
return 0;
}
使用预编译指令得到:
int square(int n)
{
return n * n;
}
int func(int x)
{
return x;
}
int main()
{
int result = 0;
result = (printf("Call function %s\n", "square"), square(4));
result = (printf("Call function %s\n", "func"), func(10));
return 0;
}
我们可以看出:#f被转换为“f”,变为字符串格式
##运算符:预处理器的粘合剂
- ## 运算符用于在预处理期粘连两个标识符
- ## 的连接作用是在预处理期完成的,因此只在宏定义中有效
- 编译器不知道 ## 的连接作用
- 用法:
#define CONNECT(a, b) a##b
int CONNECT(a, 1); //int a1;
a1 = 2;
示例代码:##运算符的工程应用
#include <stdio.h>
#define STRUCT(type) typedef struct _tag_##type type;\
struct _tag_##type
STRUCT(Student)
{
char* name;
int id;
};
int main()
{
Student s1;
Student s2;
return 0;
}
预编译得到:
typedef struct _tag_Student Student;
struct _tag_Student
{
char* name;
int id;
};