Concatenating String Literals with Strings
In C , the operator can be used to concatenate strings and string literals. However, there are limitations to this functionality that can lead to confusion.
In the question, the author attempts to concatenate the string literals "Hello", ",world", and "!" in two different ways. The first example:
<code class="cpp">const string hello = "Hello"; const string message = hello + ",world" + "!";</code>
In this case, the code compiles and runs successfully. This is because the first operand to the operator is a string object (hello), so the compiler treats this as a concatenation of a string and two string literals.
However, the second example:
<code class="cpp">const string exclam = "!"; const string message = "Hello" + ",world" + exclam;</code>
fails to compile. This is because the leftmost operator is attempting to concatenate two string literals, which is not allowed. The compiler interprets this code as:
<code class="cpp">const string message = (("Hello" + ",world") + exclam);</code>
and the first concatenation is trying to add two pointers (const char* literals) together.
To resolve this issue, the code should either:
Make one of the first two strings being concatenated a string object:
<code class="cpp">const string message = string("Hello") + ",world" + exclam;</code>
Use parentheses to force the second to be evaluated first:
<code class="cpp">const string message = "Hello" + (",world" + exclam);</code>
The reason you can't concatenate two string literals using is because string literals are stored as arrays of characters, which can't be directly added together. When you use a string literal in most contexts, it's converted to a pointer to its initial element, which is not a valid operand for the operator.
Therefore, it's important to remember that only one of the two leftmost operands in a concatenation expression can be a string literal. String literals can, however, be concatenated by placing them next to each other, as in:
<code class="cpp">"Hello" ",world" "Hello,world"</code>
The above is the detailed content of Why Did String Concatenation Using Fail with String Literals?. For more information, please follow other related articles on the PHP Chinese website!