Why can I build a string with multiple string literals?

#include <iostream>
#include <string>

int main() {
    std::string str = "hello " "world" "!";
    std::cout << str;
}

The following commands compile, run, and print:

Hello World!

watch live


It seems that string literals are concatenated together, but it is interesting that this cannot be done with operator +:

#include <iostream>
#include <string>

int main() {
    std::string str = "hello " + "world";
    std::cout << str;
}

This does not compile.
watch live


Why is this behavior in language? My theory is that it allows you to build strings with multiple operators #include, because the operators #includemust be in their own string. Is it possible that this behavior is possible due to the grammar of the language, or is it an exception that was added to solve the problem?

+3
source share
5

, ++ standard 2.2 6, :

operator +, * const char **.

, C, -C, : section 6.4.5 :

, , . (. §6.10.3), C89 . , , . C , . , , .

, :

   std::string str = "hello \
world\
!";

.

+10

@erenon, , , , :

cout << "This is a very long string-literal, "
        "which for readability in the code "
        "is divided over multiple lines.";

, , operator+, , operator+, char const *. -, string ( C-), :

string str = string("Hello ") + "world";
+7

.

+2

, "hello " + "world"; +, const char*... , .

"hello " "world" "!" . , .

0

, . , "hello world!".

, , . + .

?

This is a legacy of C that has been going on since when memory was a valuable resource. This allows you to perform quite a few string manipulations without requiring dynamic memory allocation (as is often done by more modern idioms such as std::string); the price for this is rather bizarre semantics.

0
source

All Articles