Search code examples
c++stringconcatenation

How to concatenate strings using + operator


Why one is allowed while another produce error. Anyone who can explain.

#include<string>
using namespace std;
int main()
{
    string s3 = "Why";
    string s11 = "hello" + " , " + s3;  // It gives error
    string s11 =  s3 + " , " +"hello" ; // This works fine.
}

Solution

  • Due the operator precedence, the line

    string s11 = "hello" + " , " + s3;
    

    is processed as

    string s11 = ("hello" + " , " ) + s3;
    

    The sub-expression "hello" + " , " is not legal. The first term is of type char const [6] (an array of 6 char const) and the second term is of type char const [4] (an array of 4 char const).

    There is no + operator between the two. That's why it's a compiler error.


    The second line

    string s11 =  s3 + " , " + "hello" 
    

    is processed as

    string s11 =  (s3 + " , ") + "hello" 
    

    The sub-expression s3 + " , " is valid since there is an overload of the operator+ that supports that operation. The sub-expression evaluates to a std::string. Hence, the subsequent + "hello" is also a supported operation.