C++ Adding String Literal to Char Literal

Your thought regarding the first line is correct, that’s precisely what’s happening.

There isn’t any default + operator for literal strings like "ab" so what happens is the compiler takes that (as a C-style string) and uses the const char* pointer that points to the literal. It then takes your literal character 'c' and promotes it to int with some value. This int is then added to the address of the literal and used as a C-string. Since you’ve exceeded the space allocated for your literal string, the results are undefined and it just printed out characters from the resulting address until it found a null.

If you want to create the string in one shot, you can help the compiler figure out that you wanted to convert to string first with a cast: std::string str = std::string("ab") + 'c';. Alternately (as seen in a separate comment) do it with concatenation which may or may not perform better. Use whichever seems clearer in your case: std::string str = "ab"; str += 'c';.

In the second case, you have already created a string and string has an overloaded operator+ that does the intuitive concatenation.

Leave a Comment