Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

string

char

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.

like image 904
Joe Avatar asked Apr 12 '16 17:04

Joe


1 Answers

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;
like image 170
songyuanyao Avatar answered Nov 14 '22 23:11

songyuanyao