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


here cases c++ std::string couldn't understand.

1.

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

2.

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

3.

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

4.

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

5.

in code, had line ans += to_string(q); q single digit integer. program threw runtime error.

changed ans+= (q+'0'); , error got removed.

please clearing idea.

string ans = ""+'a'; 

"" address of empty string literal. 'a' gets interpreted integer, ascii code 65. adds 65 address of literal string, results in undefined behavior, possibly crash.

ans=ans+'a'; 

ans std::string. std::string defines overloaded + operator. several, actually. 1 of them, in particular, overloads + parameter character, , appends character string.

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

5+'0' expression that's promoted int type. std::string not unambiguously overload + operator int parameter. result in compilation error.

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

std::string have unambigous overloaded += operator, compiles fine.


Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -