Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Literal String Concatenation

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'; ?

like image 922
Eric Conner Avatar asked Apr 18 '11 16:04

Eric Conner


People also ask

Can you concatenate strings in 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.

Is char * A string literal?

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.

Does C have concatenation?

As you know, the best way to concatenate two strings in C programming is by using the strcat() function.

How do you specify string literals?

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.


1 Answers

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.

like image 97
Mark B Avatar answered Sep 28 '22 21:09

Mark B