在C语言中使用##运算符连接字符串

3
在 C 语言中,我们可以使用 ## 来连接一个参数化宏的两个参数,例如:

arg1 ## arg2,返回值为 arg1arg2

我写了这段代码,希望它能够将两个字符串字面量连接起来并返回,但是我无法让它工作。
#define catstr(x, y) x##y

puts("catting these strings\t" catstr(lmao, elephant));

返回以下错误:
define_directives.c:31:39: error: expected ‘)’ before ‘lmaoelephant’
   31 |         puts("catting these strings\t" catstr(lmao, elephant));
      |                                       ^
      |                                       )

看起来字符串正在连接,但是为了使puts打印它,它们需要用引号括起来。但这样做,宏就不再起作用了。我该怎么解决这个问题?


你需要在某个地方将参数lmaoelephant转换为字符串字面量。这可能是在使用##运算符连接符号创建lmaoelephant之后,再使用#运算符。或者你可能只需要将参数转换为字符串——这会更容易。#define catstr(x, y) #x #y可以与puts("concatenating these strings; " catstr(lmao, elephant));一起使用,并在单行输出中产生concatenating these strings: lmaoelephant - Jonathan Leffler
2个回答

5

您无需使用##来连接字符串。在C中,相邻的字符串会自动拼接:"abc" "def"将变成"abcdef"

如果您想让lmaoelephant变成字符串(不知何故您不想手动加上引号),则需要使用字符串化操作符#

#define string(x) #x

puts("catting these strings\t" string(lmao) string(elephant));

1
要以这种方式使用调用puts(),宏catstr()应构建为执行两个操作:
  • lmao字符串化并连接到字符串"catting these strings\t"
  • elephant字符串化并连接到lmao中。

您可以通过更改现有的宏定义来实现此目的:

#define catstr(x, y) x##y

To:

#define catstr(x, y) #x#y

这基本上导致了以下结果:
"catting these strings\t"#lmao#elephant

或者:

"catting these strings   lmaoelephant"  

将其制作成一个单一的以空字符结尾的字符串,适用于作为puts()函数的参数:
puts("catting these strings\t" catstr(lmao, elephant));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接