Svaberg Svaberg - 4 months ago 7
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
abcdefghi
to the console. How delightful. How and why does this work?

Answer

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 " 
"world";

All produce "hello world";

Comments