In this section we will see another property of string and string literals. If we want to concatenate two strings in C++, we have to remember some of things.
If x + y is the expression of string concatenation, where x and y both are string. Then the result of this expression will be a copy of the character of string x followed by the characters of string y.
Either x or y can be a string literal or character, but not both. If both are string literal, they will not be concatenated.
Example Code
#include<iostream>
using namespace std;
main(){
cout << "Hello " + "World";
}Output
The above code will not be compiled because both of the operands are literals.
Here the left associativity of the operator ‘+’ is returning the error. If one of them is string, then it will work properly.
Example Code
#include<iostream>
using namespace std;
main(){
string my_str = "Hello ";
cout << my_str + "World";
}Output
Hello World