user3656184 user3656184 - 5 months ago 24
C Question

Why does adding a space between two strings concat the strings in c?

Sorry if I am going to ask a very basic question. I tried to search for it but I have been unable to find any answer.

When I run the following code:

#include <stdio.h>

int main() {
char *temp = "sai" "krishna";
printf("%s\n", temp);
return 0;

it prints saikrishna

Can you kindly specify why it happens? Should not we use strcat or other concatenation techniques?

Can you please refer to any documentation relating to it and where we can use this technique?


It's a language feature. C allows string literals to get concatenated at compile-time. It can be handy when you have very long string literals stretching over several lines, or when you want to break up string literals containing hex escape sequences. (For example puts("\x42AD") will translate to character 0x42AD, which is likely nonsense and unintended, as opposed to puts("\x42" "AD") which will print BAD.

strcat and strcpy are for string handling in run-time. If you have two string literals, they are compile-time constants, and may as well get concatenated by the compiler in advance, to save execution time.