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



In this article, we will explore what happens when we concatenate two string literals in C++. There are two important points to remember when concatenating strings in C++.

Concatenation is another property of the string and string literals: let's see the following two properties below:

  • If x + y is the expression of string concatenation, where x and y are both strings. Then the result of this expression will be a copy of the characters 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.

Input / Output Scenario

Following are the input and output scenario:

Input : "tutorials"+"point"
Output : It will not compile, an error will be thrown.

Explanation: In the above scenario, string literals are pointers: "tutorials" and "point" are const char* in C++. They are not actual std::string objects. The + operator is not defined for const char*.

Let's see another input/output scenario:

Input : string = "tutorials"
Input : string + "point"
Output: tutorialspoint

Let's see one more another Scenario:

string + "point" + " India"

When you use string + "point," it first joins string and "point" to create a new string. Now that this new string is no longer literal, adding "India" to it works without error.

Concatenate Two String Literal

C++ Program to illustrate two string literal can not be concatenated:

#include <iostream>
using namespace std;
int main()
{
   // this will not work
   cout<<"geeks" + "forgeeks";
   return 0;
}

We get the error if we run the above code because two string literals can not be concatenated.

Concatenate One String and One String literal

In the example, we concatenate one string and one string literal because we can not directly concatenate more than one string literal:

#include <iostream>
using namespace std;
int main()
{
   string str = "tutorialspoint";
   cout << str + " India" << endl;
   return 0;
}

Following is the output:

tutorialspoint India
Updated on: 2025-06-06T14:10:58+05:30

138 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements