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 : "geeks"+"forgeeks"
Output : It will not compile, an error will be thrown.

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

"geeks" + "forgeeks" + geekstring  

Here, left associativity of + also plays a role in creating the error as + is left associative so first “geeks” + “forgeeks” will concatenate which will create the error as discussed above.

Case 2 : We can concatenate following:

geekstring + "geeks" + "forgeeks" 

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

Input : geekstring = "geeks"
Input : geekstring + "forgeeks"
Output: geeksforgeeks
filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

geeksforgeeks
geeksforgeeks Hello


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.