Concatenating String Literals: A Closer Look
In C , the concatenation operator " " can be used to combine strings, but there are certain restrictions when working with string literals. Let's explore these restrictions and understand the semantics behind them.
As the quote from Accelerated C suggests, you cannot directly concatenate two string literals using " ". This is because string literals are stored as character arrays, and attempting to concatenate two pointers to such arrays would result in undefined behavior.
Consider the following example:
<code class="cpp">const string hello = "Hello"; const string message = hello + ",world" + "!"; // Valid</code>
In this case, hello is a const string object, which is one of the arguments to the leftmost " ". The result of this concatenation is a new string object containing "Hello,world". This new string is then concatenated with "!" to produce the final message.
However, in this example:
<code class="cpp">const string exclam = "!"; const string message = "Hello" + ",world" + exclam; // Invalid</code>
the compilation error arises because the " =" operator has left-to-right associativity. This means that the parenthesized equivalent of the expression is:
<code class="cpp">const string message = (("Hello" + ",world") + exclam);</code>
Now, "Hello" and ",world" are both string literals, and since we cannot concatenate two string literals directly, the expression ("Hello" ",world") is invalid.
To resolve this issue, we can force the second " " to be evaluated first by using parentheses:
<code class="cpp">const string message = "Hello" + (",world" + exclam);</code>
Alternatively, we can create a string object from one of the string literals:
<code class="cpp">const string message = string("Hello") + ",world" + exclam;</code>
In general, one of the first two strings being concatenated must be a std::string object.
Understanding these semantics is crucial when working with string literals in C . By following these guidelines, we can effectively concatenate strings while avoiding common pitfalls associated with string literals.
The above is the detailed content of What are the Restrictions on Concatenating String Literals in C ?. For more information, please follow other related articles on the PHP Chinese website!