一、C/C++ 宏定义 # Stringizing Operator
数字符号或“字符串化”运算符 (#) 将宏参数转换为字符串而不扩展参数定义。它只用于采用参数的宏。 如果它在宏定义中位于形参之前,则由宏调用传递的实参将用引号引起来并被视为字符串。 字符串随后替换宏定义中的字符串化运算符和形参的组合的每个匹配项。
MSDN的原文如下:https://msdn.microsoft.com/zh-cn/library/7e3a913x
The number-sign or "stringizing" operator (#) converts macro parameters to string literals without expanding the parameter definition.It is used only with macros that take arguments.If it precedes a formal parameter in the macro definition, the actual argument passed by the macro invocation is enclosed in quotation marks and treated as a string literal.The string literal then replaces each occurrence of a combination of the stringizing operator and formal parameter within the macro definition.
二、C/C++ 宏定义 ## 用于把两个参数粘贴在一起
https://msdn.microsoft.com/zh-cn/library/wy090hkc
实例1:
#include <stdio.h>
#define stringer(x) printf(#x "\n")
void main()
{
stringer(In quotes in the printf function call );
stringer( "In quotes when printed to the screen" );
stringer( "This: \" prints an escaped double quote" );
}
特别注意#这样定义的宏,不会再展开,
实例2:
#include <stdio.h>
#define f(a,b) a##b
#define g(a) #a
#define h(a) g(a)
int main()
{
printf("%s\n", h(f(1,2)));
printf("%s\n", g(f(1,2)));
return 0;
}
三、#、##中间转换
默认情况下,#,##定义的宏是不会展开的,为了达到展开的目的,必须多定义一个中间转换宏
如下:
#include<stdio.h>
#include<limits.h>
#define A 2
#define STR(s) #s
#define CAT(s1,s2) int(s1##e##s2)
int main()
{
printf("int max: %s\n",STR(INT_MAX));
printf("int max: %d\n",STR(INT_MAX));
// printf("%d\n",CAT(A,A));//error C2065: 'AeA' : undeclared identifier
return 0;
}
运行结果为:
可知,INT_MAX和A都没有在宏定义STR和CAT中展开,为了达到展开的目的,多定义一个中间转换的宏,如下所示
#include<stdio.h>
#include<limits.h>
#define A 2
#define _STR(s) #s
#define STR(s) _STR(s)
#define _CAT(s1,s2) int(s1##e##s2)
#define CAT(s1,s2) _CAT(s1,s2)
int main()
{
printf("int max: %s\n",STR(INT_MAX));
printf("int max: %d\n",STR(INT_MAX));
printf("%d\n",CAT(A,A));
return 0;
}
多定义了#define STR(s) _STR(s),#define CAT(s1,s2) _CAT(s1,s2)用于宏展开
运行结果如下:
从运行结果可知,改宏定义实现了宏展开,
STR(INT_MAX)--> _STR(2147483647)-->2147483647
CAT(A,A)-->_CAT(2,2)-->200