C/C++ 宏定义 # ##

一、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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值