Macro for concatenating two strings in C

2019-01-10 18:01发布

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 would return "idan-oop"

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

3条回答
小情绪 Triste *
2楼-- · 2019-01-10 18:03
#define space_conc(str1, str2) #str1 " " #str2
printf("%s", space_conc(hello, you)); // Will print "hello you"
查看更多
我只想做你的唯一
3楼-- · 2019-01-10 18:07

Try this

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

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"

which it'll concatenate to

"hello world"

HTH

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

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

will result in the following if called as dumb_macro(hello, world)

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'
查看更多
霸刀☆藐视天下
4楼-- · 2019-01-10 18:10

The right was to do it is to place the 2 strings one next to the other. '##' won't work. Just:

#define concatenatedstring string1 string2
查看更多
登录 后发表回答