Why is it that we can use the + operator to concatenate string variables but not string literals? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

Why is it that we can use the + operator to concatenate string variables but not string literals?

23rd Feb 2019, 8:18 AM
Moses Odhiambo
Moses Odhiambo - avatar
4 Answers
+ 8
ShortCode sorry about that, I think the network here is slow or something
23rd Feb 2019, 8:21 AM
Moses Odhiambo
Moses Odhiambo - avatar
+ 5
The usual literals are not std::string literals. They are raw character arrays of a constant size. (called c-strings). The string class has overloaded operators as members and friends to support concatenation with other strings and c-strings. But since no overload of + exists for concatenating two c-strings, you get an error when you try to perform "Hello"+" World" or a similar operation. The workaround for this would be to either wrap one of the c-strings inside a string object and then concatenate it with the other literals, or use the literal operator""s to create std::string literals. For the first solution: std::string s3 = "Hello"+std::string(" there!"); And for the second: std::string s4 = "Hello"+" there!"s; The second solution uses the operator ""s to initialize a constant c-string as a std::string object, which can be concatenated to other literals. Literals are available since C++11, and are accessible when you use the std::literals namespace. (using namespace std::literals)
23rd Feb 2019, 9:37 AM
Kinshuk Vasisht
Kinshuk Vasisht - avatar
+ 4
Are you asking this twice Moses Odhiambo?
23rd Feb 2019, 8:20 AM
ShortCode
+ 4
Moses Odhiambo its okay. I often got that too!
23rd Feb 2019, 8:26 AM
ShortCode