C string concatenation of constants

Frank Vilea picture Frank Vilea · Apr 24, 2012 · Viewed 19.6k times · Source

One of the answers to Why do you not use C for your web apps? contains the following:

For the C crap example below:

const char* foo = "foo";
const char* bar = "bar";
char* foobar = (char*)malloc(strlen(foo)+strlen(bar)+1);
strcpy(foobar, foo);
strcat(foobar, foo);

Actually, constants CAN AND SHOULD be concatenated naturally in C:

const char foo[] = "foo";
const char bar[] = "bar";
char foobar[] = foo bar; // look Ma, I did it without any operator!

And using [] instead of * will even let you modify the string, or find their length:

int foo_str_len = sizeof(foobar)-1;

So, PLEASE, before you (falsely) claim that C is difficult to use with strings, learn how to use C.


I've tried it myself but get an error:

expected ‘,’ or ‘;’ before string constant

So my question is: Do I need to tell the compiler something in order to make this work or is the above post simply wrong? Please note that I'm aware of other ways to concatenate character arrays in C.

Answer

Lundin picture Lundin · Apr 24, 2012

(char*)malloc

Never typecast the result of malloc in C. Read this and this.

Actually, constants CAN AND SHOULD be concatenated naturally in C

No, string literals can and should be concatenated in C. "foo" is a string literal and const char foo[] is a constant string (array of characters). The code "foo" "bar" will concatenate automatically, the code foo bar will not.

If you want, you can hide the string literals behind macros:

#define foo "foo"
#define bar "bar"
char foobar[] = foo bar; // actually works

So, PLEASE, before you (falsely) claim that C is difficult to use with strings, learn how to use C.

C is rather difficult to use with strings, as we can see from this very example. Despite their arrogant confidence, the person who wrote it mixed up the various concepts and still has to learn how to use C.