1

In the definition of s6 and s7, how is there a string for every + in s6 and how come it's not still so in s7?

#include <string>
using std::string;
int main()
{
string s1 = "hello", s2 = "world";
string s3 = s1 + ", " + s2 + '\n';
string s4 = s1 + ", "; // ok: adding a string and a literal
string s5 = "hello" + ", "; // error: no string operand
string s6 = s1 + ", " + "world"; // ok: each + has a string operand
string s7 = "hello" + ", " + s2; // error: can't add string literal
}
Jake Wright
  • 373
  • 1
  • 8

4 Answers4

3

[expr.add]p1:

The additive operators + and - group left-to-right. [...]

+ and - are left associative, that means that actually, the last two definitions look like this:

string s6 = (s1 + ", ") + "world";
string s7 = ("hello" + ", ") + s2;

Now the error is obvious: "hello" + ", " is evaluated first, but because there is no addition operator for const char[], you get a compiler error. If the operators were right associative, s7 would be valid, while s6 would not.

Rakete1111
  • 47,013
  • 16
  • 123
  • 162
2

This is due to the + operator having left to right associativity.

Find a better description of this here: Concatenate two string literals

1

There is a difference between the notion of a "string literal" such as "hello" and ", " and a "std::string object".

String literals are just char[] and adding two to each other doesn't have the effect you think it has. You're just adding the two pointers, which doesn't amount to anything meaningful in your case.

On the other hand, the operator+() method is defined on operands std::string and char* such that it returns a std::string object. This is when the other concept you are missing comes into play: operator associativity. In the case of the following line:

string s6 = s1 + ", " + "world";
  1. s1 + ", " returns a std::string
  2. That returned object is concatenated to "world", also returning a std::string object. This works as expected

On the other hand, the following statement:

string s7 = "hello" + ", " + s2;

Does not work as expected because the first part of the expression being evaluated is "hello" + ", ", which is an attempt to add 2 string literals.

Nasser Al-Shawwa
  • 3,573
  • 17
  • 27
0

There is no need to add string literals "hello" ", " will be glued by preprocessor to "hello, ".

user7860670
  • 35,849
  • 4
  • 58
  • 84