Combine string literal with char literal

I want to execute a string literal and a char literal. Syntactically incorrect, "abc" 'd' "efg" displays a compiler error:

xc: 4: 24: error: expected ',' or ';' to 'd'

For now, I should use snprift (optional), even though the value of the string literal and char literal are known at compile time.

I tried

 #define CONCAT(S,C) ({ \ static const char *_r = { (S), (C) }; \ _r; \ }) 

but this does not work because the null delimiter S not split. (Besides providing 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") ?

If someone asks why I want this: the char literal comes from the library, and I need to print the line as a status message.

+8
c macros string char concatenation
source share
4 answers

If you can live with the only quotes included in it, you can use string encoding:

 #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, which may or may not be appropriate, but as far as it is convinced that it is actually a string literal, this is the only way that comes to mind without formatting at run time.

+6
source share

Try it. It uses the C macro of double macros, so the macro argument has the ability to expand before it is compressed.

 #include <stdio.h> #define C d #define S "This is a string that contains the character " #define STR(s) #s #define XSTR(s) STR(s) const char* str = S XSTR(C); int main() { puts(str); return 0; } 
+3
source share

I came up with a GCC-specific solution that I don't really like, since you cannot use CONCAT nested.

 #include <stdio.h> #define CONCAT(S1,C,S2) ({ \ static const struct __attribute__((packed)) { \ char s1[sizeof(S1) - 1]; \ char c; \ char s2[sizeof(S2)]; \ } _r = { (S1), (C), (S2) }; \ (const char *) &_r; \ }) int main(void) { puts(CONCAT ("abc", 'd', "efg")); return 0; } 

http://ideone.com/lzEAn

+3
source share

C will allow you to concatenate string literals. In fact, there is nothing wrong with snprintf() . You can also use strcpy() :

 strcpy(dest, str1); dest[strlen(dest)] = c; strcpy(dest + strlen(dest) + 1, str2); 

You can also use the giant switch to overcome this limitation:

 switch(c) { case 'a': puts("part1" "a" "part2"); break; case 'b': puts("part1" "b" "part2"); break; /* ... */ case 'z': puts("part1" "z" "part2"); break; } 

... but I refuse to claim authorship.

In short, just stick with snprintf() .

+2
source share

All Articles