Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a string literal and a character literal be concatenated?

Why does name misbehave in the following C++ code?

string name =  "ab"+'c';

How would the equivalent code behave in Java/C#?

like image 629
yesraaj Avatar asked Nov 28 '22 04:11

yesraaj


1 Answers

Try

std::string name = "ab" "c";

or

std::string name = std::string("ab") + c;

In C++, "ab" is not a std::string, but rather a pointer to a string of chars. When you add an integral value to a pointer, you get a new pointer that points farther down the string:

char *foo = "012345678910121416182022242628303234";
std::string name = foo + ' '; 

name gets set to "3234", since the integer value of ' ' is 32 and 32 characters past the begining of foo is four characters before the end of the string. If the string was shorter, you'd be trying to access something in undefined memory territory.

The solution to this is to make a std:string out of the character array. std:strings let you append characters to them as expected:

std::string foo = "012345678910121416182022242628303234";
std::string name = foo + ' '; 

name gets set to "012345678910121416182022242628303234 "

like image 144
Eclipse Avatar answered Apr 05 '23 23:04

Eclipse