Understanding String Concatenation in C++: Adding Literals and Strings
But "hello" + str + ", " is legal !!

Understanding String Concatenation in C++: Adding Literals and Strings

Introduction

In C++, we often find ourselves needing to combine strings and literals. However, the rules for doing so can sometimes be a bit tricky. Let’s dive into the details.


The Basics of String Concatenation

In C++, the + operator is used for string concatenation. This means that we can combine two strings into one. For example:

string s1 = "hello",  s2 = "world" ;

string s3 = s1 + ", " + s2 + '\n' ;        

In the above code, s1, s2, and the literals are all of type string. Therefore, they can be combined using the + operator.


Mixing Strings and Literals

When we mix strings and string or character literals, at least one operand to each + operator must be of string type. Here are some examples:

string s4 = s1 + ", " ;   // ok: adding a string and a literal

string s5 = "hello" + ", " ;   // error: no string operand        

In the initialization of s4, we are adding a string (s1) and a literal, which is allowed. However, in the initialization of s5, we are trying to add two literals, which is not allowed because there is no string operand.


Chaining String Concatenation

Things can get a bit more complex when we chain together multiple concatenations:

string s6 = s1 + ", " + "world" ;  // ok: each + has a string operand

string s7 = "hello" + ", " + s2 ;  // error: can’t add string literals        

In the initialization of s6, each + operator has a string operand, so the concatenation is allowed. This works in much the same way as when we chain together input or output expressions. The expression groups as (s1 + ", ") + "world", and the subexpression s1 + ", " returns a string, which forms the left-hand operand of the second + operator.

On the other hand, the initialization of s7 is illegal. If we parenthesize the expression as ("hello" + ", ") + s2, we can see that the first subexpression adds two string literals, which is not allowed.


A Note on String Literals

For historical reasons, and for compatibility with C, string literals are not standard library strings. It is important to remember that these types differ when you use string literals and library strings.

In conclusion, when working with strings and literals in C++, it’s crucial to understand the rules of string concatenation. Always ensure that at least one operand to each + operator is of string type and remember that string literals are not standard library strings. Happy coding!



要查看或添加评论,请登录

Ali El-bana的更多文章

社区洞察

其他会员也浏览了