Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String plus Char - what is happening?

Tags:

c++

string

char

I'm just curious about what is going on when trying to add a char to a string.

Initially, I thought it would work like a concatenation but it didn't:

cout<<"ab"+'a'<<endl;
cout<<""+'a'<<endl;

Prints

enter image description here

However,

cout<<"bla"<<endl;
cout<<"ab"+'a'<<endl;
cout<<""+'a'<<endl;

Prints

enter image description here

like image 890
fersarr Avatar asked Dec 29 '25 17:12

fersarr


1 Answers

String literals are char const[N] (decays to char const *), and char is a small range integer type. You're doing pointer arithmetic.

like image 74
just somebody Avatar answered Dec 31 '25 07:12

just somebody