Svaberg Svaberg - 2 months ago 6x
C++ Question

c++ string concatenation by juxtaposition

I came across this phenomenon today when giving string literals as argument to a function and forgetting a comma:

std::string str = "Hello " "world";
std::cout << str << std::endl;

which compiles and prints
Hello world
to the console. It also works for

char chr[] = "abc" "def" "ghi";
std::cout << chr << std::endl;

which prints
to the console. How delightful. How and why does this work?


This is behavior covered by [lex.phases]/6

Adjacent string literal tokens are concatenated.

So before the compiler actually starts to compile the code all string literals that are only separated why white space are concatenated together.

"hello " "world";
"hello "                  "world";
"hello " 

All produce "hello world";