Joe
Joe

Reputation: 410

Why return an unknown value when I added a char to null string (as "" + c)?

Allow me to show you my code first:

void testStringAdd(){
   char c = '$';
   string str = "";
   str += c;//the same as `str = str + c;`
   cout << str << "---";
   cout << "size : " << str.size() << endl;
   str = "" + c;//the same as `str = c + ""`;
   cout << str << "---";
   cout << "size : "<< str.size() << endl;
}

I expected the output is:

$---size : 1

$---size : 1

But the real output on vs2013 is:

$---size : 1

---size : 0

This is an interesting phenomenon, and I wonder why it is so weird?

note: If I code string str = ""; then str == "" will return true.

Upvotes: 5

Views: 585

Answers (1)

songyuanyao
songyuanyao

Reputation: 172924

In str = "" + c;, "" is not std::string, it's a string literal with type const char[], and then decay to const char* and "" + c becomes pointer arithmetic.

In this case, since c has a positive value, "" + c will lead to UB, which means anything is possible. It might be lucky (or unlucky) for you the program doesn't crash.

And as the comments pointed, an explicit conversion to std::string will fix the issue.

str = std::string("") + c;

Or use std::string literal operator (since C++14):

str = ""s + c;

Upvotes: 9

Related Questions