Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ operator order evaluation

I have the code and it gives me a compilation error. I expected left-right operator order evaluation. The result of 'name += ":"' is string, but it looks like it evaluated ":" + "O" first. I didn't find any clear explanation why.

#include <string>

int main()
{
  std::string name("HELL");
  name += ":" + "O";
  std::cout << "Hello, " << name << "!\n";
}
like image 607
Николай Горбачук Avatar asked Dec 06 '25 05:12

Николай Горбачук


2 Answers

The expression name += ":" + "O" is grouped as name += (":" + "O")

But this will result in a compilation error since ":" and "0" are const char[2] types that decay to const char* pointers in that expression; and pointers cannot be summed!

From C++14 you could put the + into "string mode" with a user-defined-literal ""s:

name += ""s + ":" + "O"

The grouping rules are hardwired into the language grammar, although it's convenient to think in terms of operator precedence and associativity.

like image 111
Bathsheba Avatar answered Dec 08 '25 19:12

Bathsheba


According to operator precedence, operator+ has higher precedence than operator+=, then name += ":" + "O"; is interpreted as name += (":" + "O");, while ":" + "O" is invalid, you can't add two pointers (":" and "O" would decay to pointer with type const char*).

You can add () to specify precedence, e.g. (name += ":") + "O";, it compiles but note that the part + "O" becomes meaningless here. Or you might want (name += ":") += "O"; as @Scheff suggested, it depends on your demand.

like image 37
songyuanyao Avatar answered Dec 08 '25 19:12

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!