2

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

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
fersarr
  • 3,399
  • 3
  • 28
  • 35

5 Answers5

8

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

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
just somebody
  • 18,602
  • 6
  • 51
  • 60
2

Note that the storage type of a string in C and C++ is char* or char[]. That is, a string in C or C++ is just an array of characters (pointers and arrays in C/C++ are essentially the same).

When you do "ab"+'a', "ab" is compiled to a pointer to a fixed string somewhere in memory, and 'a' is compiled to the integer of its ascii value (96). The "ab" is then a pointer to the location of the string in memory, and when you do "ab"+'a', the result is a pointer to the location 96 bytes after the start of your string. The cout then tries to print whatever data is at that location, which in this case is unprintable.

zstewart
  • 2,093
  • 12
  • 24
1

The string is converted to a "char *", and then the ascii value of 'a' (96) is added to that character. You're now outputting characters beyond the end of the string.

If you're trying to concatenate two strings, see Append Char To String in C? for some more information.

Community
  • 1
  • 1
Daniel
  • 4,481
  • 14
  • 34
0

you are printing out the arithmetic result of adding memory values of a string and a char.

miushock
  • 1,087
  • 7
  • 19
0

"ab" is a string literal of type const char [3] and it decays to a const char* due to type decay when used in the expression "ab" + 'a'.

+ is an arithmetic operator and so the character literal 'a' is promoted to an int.

Thus essentially, you're doing pointer arithmetic. In particular, you're adding the promoted int value to the decayed const char*. Since std::ostream has an overloaded operator<<:

template< class Traits >
basic_ostream<char,Traits>& operator<<( basic_ostream<char,Traits>& os,  
                                        const char* s );

It will be used. That is, the argument to the parameter named s will be the result of adding the promoted int value to the decayed const char*.

Jason
  • 36,170
  • 5
  • 26
  • 60