在 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
打印它,它们需要用引号括起来。但这样做,宏就不再起作用了。我该怎么解决这个问题?
lmao
和elephant
转换为字符串字面量。这可能是在使用##
运算符连接符号创建lmaoelephant
之后,再使用#
运算符。或者你可能只需要将参数转换为字符串——这会更容易。#define catstr(x, y) #x #y
可以与puts("concatenating these strings; " catstr(lmao, elephant));
一起使用,并在单行输出中产生concatenating these strings: lmaoelephant
。 - Jonathan Leffler