I have a question about string concatenation in C++.
string str = "ab" + 'c';
cout << str << endl;
char ch = 'c';
string str1 = "ab";
string str2 = str1 + ch;
cout << str2 << endl;
The code produces:
ed before SaveGraphicsState
abc
Can someone explain the processing of this line: string str = "ab" + 'c';
?
In C, the strcat() function is used to concatenate two strings. It concatenates one string (the source) to the end of another string (the destination). The pointer of the source string is appended to the end of the destination string, thus concatenating both strings.
String literals are convertible and assignable to non-const char* or wchar_t* in order to be compatible with C, where string literals are of types char[N] and wchar_t[N]. Such implicit conversion is deprecated.
As you know, the best way to concatenate two strings in C programming is by using the strcat() function.
A "string literal" is a sequence of characters from the source character set enclosed in double quotation marks (" "). String literals are used to represent a sequence of characters which, taken together, form a null-terminated string. You must always prefix wide-string literals with the letter L.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With