-1

Consider the following string definitions:

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

The book C++ Primer 5e states that the third line will cause the compiler to give an error because you cannot add string literals. The actual error given from the compiler is

error: invalid operands of types 'const char [6]'
and 'const char [3]' to binary 'operator+'

But isn't the second string s6 doing the exact same thing as s7? What is the difference?

Jinzu
  • 1,325
  • 2
  • 10
  • 22
  • 1
    Duplicate of [Concatenate two string literals](https://stackoverflow.com/questions/6061648/concatenate-two-string-literals), including discussion of left-associativity. – Raymond Chen May 31 '19 at 01:09

1 Answers1

1

Since addition associates left-to-right, s6 is parsed as (s1 + ", ") + "world". This adds a string to a const char *, resulting in another string. Then we add another const char * to that string, resulting in a third string that is stored in s6.

s7 is parsed as ("hello" + ", ") + s2, which tries to add a const char * to another const char *, which you can't do. You could rewrite it as "hello" + (", " + s2) and it would then compile.

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56