Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

c - Concatenate string literal with char literal

I want to concat a string literal and char literal. Being syntactically incorrect, "abc" 'd' "efg" renders a compiler error:

x.c:4:24: error: expected ',' or ';' before 'd'

By now I have to use snprift (needlessly), despite the value of string literal and the char literal being know at compile time.

I tried

#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.)

Is there a way to write a macro to use

  • "abc" MACRO('d') "efg" or
  • MACRO1(MACRO2("abc", 'd'), "efg") or
  • MACRO("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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...