What happen if we concatenate two string literals in C++?

If you are going to perform concatenation in C++, some of the things you must be kept in mind are:

  • If a+b is an expression that is showing string concatenation, then the result of the expression will be a copy of the character in ‘a’ followed by the character in ‘b’.
  • Either ‘a’ or ‘b’ can be string literal or a value of type char but not both. That’s why the following concatenation doesn’t throw an error but above one does.

For Example:

Input : "Beginner"+"forBeginner"
Output : It will not compile, an error will be thrown.

Case 1 : Due to the above reasons, we can not concatenate following expression:

"Beginner" + "forBeginner" + Beginnertring  

Here, left associativity of + also plays a role in creating the error as + is left associative so first “Beginner” + “forBeginner” will concatenate which will create the error as discussed above. Case 2 : We can concatenate following:

Beginnertring + "Beginner" + "forBeginner" 

Here, left associativity will not create the error as it will join Beginnertring and “Beginner” making it not a literal then “forBeginner” will be added and no error will be generated.

Input : Beginnertring = "Beginner"
Input : Beginnertring + "forBeginner"
Output: w3wiki

CPP




// Program to illustrate two string
// literal can not be concatenate
#include <iostream>
using namespace std;
int main()
{
    string Beginnertring = "Beginner";
    cout << Beginnertring + "forBeginner" << endl;
 
    // while this will not work
    // cout<<"Beginner" + "forBeginner";
 
    // this will work
    cout << Beginnertring + "forBeginner" + " Hello";
 
    // but again this will not work
    // cout<<"forBeginner" + "hello" + Beginnertring;
    return 0;
}


Output:

w3wiki
w3wiki Hello

Time complexity : O(1)

Space complexity : O(n)