C++ String Concatenation
Posted on April 18th, 2011 in C++ | No Comments »
This is an interesting note about how strings are handled in C++. It turns out that if you attempt to concatenate a string literal and a character, you don’t get the result you expect.
string str = "ab" + 'c'; cout << str << endl; char ch = 'c'; string str1 = "ab"; string str2 = str1 + ch; cout << str2 << endl;
This code produces the following output:
ed before SaveGraphicsState abc
The first value printed is obviously not the concatenation we expected. Now, this difference occurs because the C++ string class overloads the + operator. When we use the string literal "ab" the compiler interprets this value as a const char* (a C-style string). When we attempt to add 'c' to it, the compiler converts the character to its integer equivalent and adds it to the char* pointer. Our string now points at some different location in memory and when we print it out it simply prints whatever it found there up to a null value.



