我想连接字符串文字和字符文字.由于语法不正确,"abc" 'd' "efg" 会导致编译器错误:
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; })但它不起作用,因为 S 的空终止符没有被剥离.(除了给出编译器警告.)
but it does not work because the null terminator of S is not stripped. (Besides of giving compiler warnings.)
有没有办法写一个宏来使用
Is there a way to write a macro to use
- "abc" MACRO('d') "efg" 或
- MACRO1(MACRO2("abc", 'd'), "efg") 或
- MACRO("abc", 'd', "efg") ?
- "abc" MACRO('d') "efg" or
- MACRO1(MACRO2("abc", 'd'), "efg") or
- MACRO("abc", 'd', "efg") ?
如果有人问我为什么要这样:char 字面量来自库,我需要将字符串作为状态消息打印出来.
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; }取决于可能合适或不合适的上下文,但就以这种方式说服它实际上是字符串文字而言,这是在运行时无需格式化的唯一方法.
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.
更多推荐
将字符串文字与 char 文字连接起来
发布评论