I am reading Accelerated C++ by Koenig. He writes that "the new idea is that we can use + to concatenate a string and a string literal - or, for that matter, two strings (but not two string literals).
Fine, this makes sense I suppose. Now onto two separate exercises meant to illuminate this .
Are the following definitions valid?
const string hello = "Hello";
const string message = hello + ",world" + "!";
Now, I tried to execute the above and it worked! So I was happy.
Then I tried to do the next exercise;
const string exclam = "!";
const string message = "Hello" + ",world" + exclam;
This did not work. Now I understand it has something to do with the fact that you cannot concatenate two string literals, but I don't understand the semantic difference between why I managed to get the first example to work (isn't ",world" and "!" two string literals? Shouldn't this not have worked?) but not the second.
This question is related to
c++
string
syntax
operators
concatenation
You should always pay attention to types.
Although they all seem like strings, "Hello"
and ",world"
are literals.
And in your example, exclam
is a std::string
object.
C++ has an operator overload that takes a std::string
object and adds another string to it. When you concatenate a std::string
object with a literal it will make the appropriate casting for the literal.
But if you try to concatenate two literals, the compiler won't be able to find an operator that takes two literals.
Your second example does not work because there is no operator +
for two string literals. Note that a string literal is not of type string
, but instead is of type const char *
. Your second example will work if you revise it like this:
const string message = string("Hello") + ",world" + exclam;
The difference between a string (or to be precise, std::string
) and a character literal is that for the latter there is no +
operator defined. This is why the second example fails.
In the first case, the compiler can find a suitable operator+
with the first argument being a string
and the second a character literal (const char*
) so it used that. The result of that operation is again a string
, so it repeats the same trick when adding "!"
to it.
In case 1, because of order of operations you get:
(hello + ", world") + "!" which resolves to hello + "!" and finally to hello
In case 2, as James noted, you get:
("Hello" + ", world") + exclam which is the concat of 2 string literals.
Hope it's clear :)
Since C++14 you can use two real string literals:
const string hello = "Hello"s;
const string message = hello + ",world"s + "!"s;
or
const string exclam = "!"s;
const string message = "Hello"s + ",world"s + exclam;
Source: Stackoverflow.com