Skip to content

Store multiple strings in a char array in C

An answer to this question on Stack Overflow.

Question

Today I saw a usage of char in C as followed:

const char temp[] = "GET / HTTP/1.0\r\n"
                        "Host:www.google.com\r\n"
                        "\r\n";

At first, I thought there would be a compile error, but actually it passed the compilation!
So can someone please tell me why it can work?
I am a fresh man learning C programming.
Thanks so much!

Answer

C has string literal concatenation, meaning that adjacent string literals are concatenated at compile time; this allows long strings to be split over multiple lines, and also allows string literals resulting from C preprocessor defines and macros to be appended to strings at compile time.

For instance:

printf(__FILE__ ": %d: Hello "
       "world\n", __LINE__);

will expand to

printf("helloworld.c" ": %d: Hello "
       "world\n", 10);

which is syntactically equivalent to

printf("helloworld.c: %d: Hello world\n", 10);