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";
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With