Wee*_*ezy 3 c concatenation c-strings string-concatenation preprocessor-directive
在 C 中,我们可以使用 ## 连接参数化宏的两个参数,如下所示:
arg1##arg2返回arg1arg2
我写了这段代码,希望它能连接并返回一个字符串文字,但我无法让它工作:
#define catstr(x, y) x##y
puts("catting these strings\t" catstr(lmao, elephant));
Run Code Online (Sandbox Code Playgroud)
返回以下错误:
define_directives.c:31:39: error: expected ‘)’ before ‘lmaoelephant’
31 | puts("catting these strings\t" catstr(lmao, elephant));
| ^
| )
Run Code Online (Sandbox Code Playgroud)
似乎字符串正在连接,但它们需要用引号括起来才能puts打印出来。但是这样做,宏不再起作用。我该如何解决这个问题?
您不需要使用##来连接字符串。C 已经连接了相邻的字符串:"abc" "def"将变为"abcdef".
如果您想要lmao并elephant成为字符串(出于某种原因而没有将它们自己放在引号中),您需要使用 stringize 运算符,#:
#define string(x) #x
puts("catting these strings\t" string(lmao) string(elephant));
Run Code Online (Sandbox Code Playgroud)