Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ character concatenation with std::string behavior. Please explain this

Tags:

c++

string

Here are some cases about c++ std::string which I couldn't understand.

1.

string ans = ""+'a';
cout << ans << endl; //Prints _string::copy

2.

string ans="";
ans=ans+'a';
cout << ans << endl; //Prints a

3.

string ans="";
ans = ans + (5 + '0'); // Throws error

4.

string ans="";
ans += (5 + '0'); //works

5.

In a code, I had the line ans += to_string(q); q was a single digit integer. The program threw runtime error.

Changed it to ans+= (q+'0'); and the error got removed.

Please help with clearing the idea.

like image 673
BitFlip Avatar asked Sep 01 '26 02:09

BitFlip


1 Answers

string ans = ""+'a';

"" is an address of an empty string literal. 'a' gets interpreted as an integer, ASCII code 65. This adds 65 to an address of a literal string, which results in undefined behavior, possibly a crash.

ans=ans+'a';

ans is a std::string. std::string defines an overloaded + operator. Several, actually. One of them, in particular, overloads + where the parameter is a character, and it appends the character to the string.

ans = ans + (5 + '0'); // Throws error

5+'0' is an expression that's promoted to an int type. std::string does not unambiguously overload the + operator with an int as the parameter. This result in a compilation error.

ans += (5 + '0'); //works

std::string does have an unambigous overloaded += operator, so this compiles fine.

like image 106
Sam Varshavchik Avatar answered Sep 03 '26 18:09

Sam Varshavchik



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!