1. ## 连接操作
##将两个字符串拼接在一起;
如下,x##y输出结果为xy,x和y表示其各自对应的字符串
#define COMBINESTR(x,y) x##y
int main ()
{
int n = COMBINESTR(123,456);
printf("n = %d\n", n);
char* pStr = COMBINESTR("abc","def");
printf("pStr = %s\n", pStr);
return 0;
}
效果:
2. #@ 字符化操作
将传入的变量x,转换成字符形式;
比如数字1转换成字符后,就是‘1’;
需要注意一下,该转换最大接受4位数;
若传入参数超过4位,编译将会存在问题;
另外,传入参数若为2位或2位以上的数值,将转化个位数字为字符,即最右边的数字转换为字符;
#define IntToChar(x) #@x
int main ()
{
#if 1 // "#@" Test
// 输出为 c = 5
char c = IntToChar(5);
printf("c = %c\n", c);
// 由于char只能表示一个字符,如果把传入的参数为2位数或者更多位数会怎么样??
// 传入5位数;报错:error C2015: too many characters in constant
// 传入4位数;输出为 c = 8
c = IntToChar(2768);
printf("c = %c\n", c);
return 0;
#endif
}
效果:
3. # 字符串化操作符
将数字转换成字符串;
看下示例:
#define IntToString( x ) #x
int main ()
{
char c[5] = IntToString(5);
printf("c = %s\n", c);
char n[5] = IntToString(2768);
printf("n = %s\n", n);
return 0;
}
输出结果: