宏在C连接两个字符串 [英] Macro for concatenating two strings in C

查看:849
本文介绍了宏在C连接两个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图确定哪些是假设需要2字符串值并返回它们串联与他们之间有一个空格的宏。看来我可以使用任何字符我想,除了空间,例如:

I'm trying to define a macro which is suppose to take 2 string values and return them concatenated with a one space between them. It seems I can use any character I want besides space, for example:

#define conc(str1,str2) #str1 ## #str2 
#define space_conc(str1,str2) conc(str1,-) ## #str2

space_conc(idan,oop);

space_conc 将返回IDAN接力

我想要的东西,返回IDAN空中接力,建议?

I want something to return "idan oop", suggestions?

推荐答案

试试这个

#define space_conc(str1,str2) #str1 " " #str2

在'##'是用来连接符号,而不是字符串。字符串可以简单地用C并列,编译器将它们连接起来,这是这个宏做什么。首先打开str1和str2的成字符串(让我们说你好和世界,如果你像这样使用 space_conc(你好,世界)),并把它们彼此相邻与简单的单空间,串其间。也就是说,所得到的扩张将是由编译器这样PTED间$ P $

The '##' is used to concatenate symbols, not strings. Strings can simply be juxtaposed in C, and the compiler will concatenate them, which is what this macro does. First turns str1 and str2 into strings (let's say "hello" and "world" if you use it like this space_conc(hello, world)) and places them next to each other with the simple, single-space, string inbetween. That is, the resulting expansion would be interpreted by the compiler like this

"hello" " " "world"

它会串连到

"hello world"

心连心

修改的结果
为了完整起见,在宏展开了##运算符用于这样的,假设你有

Edit
For completeness, the '##' operator in macro expansion is used like this, let's say you have

#define dumb_macro(a,b) a ## b

将导致如果称为 dumb_macro以下(你好,世界)

helloworld

这是不是一个字符串,而是一个符号,你可能有一个未定义的符号错误说的HelloWorld不存在的,除非你先定义它结束了。这将是合法的:

which is not a string, but a symbol and you'll probably end up with an undefined symbol error saying 'helloworld' doesn't exist unless you define it first. This would be legal:

int helloworld;
dumb_macro(hello, world) = 3;
printf ("helloworld = %d\n", helloworld); // <-- would print 'helloworld = 3'

这篇关于宏在C连接两个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆