在c语言的宏中
1. #的作用是将宏参数字符串化,用例子说明比较直观。
例如下面的宏定义
#define STR( s ) #s
那么在程序中
printf("The string is %s/n", STR(OPEN) );
会被展开成
printf("The string is %s/n", "OPEN" );
也就是说,会对#后跟的参数加引号,使其变成一个字符串。
2. ##的作用是对文本进行连接
例如下面的宏定义
#define CONS( a, b ) a##e##b
那程序中
printf("the number is %d/n", CONS(2,3) );
会被展开成
printf("the number is %d/n", 2e3 );
需要注意的是,在有#和##的宏中,如果参数本身是宏,则这个参数宏不会展开。
加一层中间转换宏可以解决这个问题。
#define _STR(s) #s
#define STR(s) _STR(s) // 转换宏
#define _CONS(a,b) int(a##e##b)
#define CONS(a,b) _CONS(a,b) // 转换宏