置字符串字面量字符字面 [英] Concatenate string literal with char literal
问题描述
我要Concat的字符串文字和char文字。作为语法不正确,ABCDEFG
呈现一个编译器错误:
I want to concat a string literal and char literal. Being syntactically incorrect, "abc" 'd' "efg"
renders a compiler error:
x.c:4:24:错误:预期','或';'前D
x.c:4:24: error: expected ',' or ';' before 'd'
现在我必须使用snprift(不必要的),尽管字符串字面值和字符文字之中知道在编译时。
By now I have to use snprift (needlessly), despite the value of string literal and the char literal being know at compile time.
我试过
#define CONCAT(S,C) ({ \
static const char *_r = { (S), (C) }; \
_r; \
})
但它不工作,因为取值
的空终止,不会被剥离。 (除了给予编译器警告。)
but it does not work because the null terminator of S
is not stripped. (Besides of giving compiler warnings.)
有没有写宏使用方式
-
ABCMACRO('D')EFG
或 -
MACRO1(MACRO2(ABC,D),EFG)
或 -
MACRO(ABC,D,EFG)
?
"abc" MACRO('d') "efg"
orMACRO1(MACRO2("abc", 'd'), "efg")
orMACRO("abc", 'd', "efg")
?
在万一有人问,为什么我想的是:该字符文字来自图书馆,我需要打印字符串作为一个状态消息
In case someone asks why I want that: The char literal comes from a library and I need to print the string out as a status message.
推荐答案
如果你可以用被包含在其中的单引号生活,你可以使用字符串化:
If you can live with the single quotes being included with it, you could use stringification:
#define SOME_DEF 'x'
#define STR1(z) #z
#define STR(z) STR1(z)
#define JOIN(a,b,c) a STR(b) c
int main(void)
{
const char *msg = JOIN("Something to do with ", SOME_DEF, "...");
puts(msg);
return 0;
}
根据,可能会或可能不适合,但就说服它实际上是一个字符串buitl这样的背景下,它是自带没有在运行时格式化想到的唯一办法。
Depending on the context that may or may not be appropriate, but as far as convincing it to actually be a string literal buitl this way, it's the only way that comes to mind without formatting at runtime.
这篇关于置字符串字面量字符字面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!