Search code examples
c++compilationstring-concatenationstring-literals

Compilation of string literals


Why can two string literals separated by a space, tab or "\n" be compiled without an error?

int main()
{
   char * a = "aaaa"  "bbbb";
} 

"aaaa" is a char* "bbbb" is a char*

There is no specific concatenation rule to process two string literals. And obviously the following code gives an error during compilation:

#include <iostream>
int main()
{
   char * a = "aaaa";
   char * b = "bbbb";
   std::cout << a b;
}

Is this concatenation common to all compilers? Where is the null termination of "aaaa"? Is "aaaabbbb" a continuous block of RAM?


Solution

  • If you see e.g. this translation phase reference in phase 6 it does:

    Adjacent string literals are concatenated.

    And that's exactly what happens here. You have two adjacent string literals, and they are concatenated into a single string literal.

    It is standard behavior.

    It only works for string literals, not two pointer variables, as you noticed.