Concatenating Strings and Characters in C
When concatenating strings and characters in C , unexpected behavior can occur. To understand this, let's examine the example:
<code class="cpp">string str = "ab" + 'c'; cout << str << endl;</code>
Here, we intend to add the character 'c' to the string "ab." However, the result is undefined behavior, leading to seemingly random output.
This behavior stems from the lack of a default operator for string literals ("ab") and character literals ('c'). Instead, the compiler interprets "ab" as a C-style string and promotes 'c' to an int. The int is then added to the address of the string literal, resulting in accessing memory outside its bounds and printing unexpected characters until a null character is encountered.
To avoid this issue, we can explicitly cast the string literal to a string:
<code class="cpp">string str = std::string("ab") + 'c';</code>
Alternatively, we can use concatenation:
<code class="cpp">string str = "ab"; str += 'c';</code>
In contrast, the second example with "ab" being a string already created works as expected:
<code class="cpp">char ch = 'c'; string str1 = "ab"; string str2 = str1 + ch;</code>
String classes typically have an overloaded operator that handles concatenation intuitively.
The above is the detailed content of Why Does Concatenating String Literals and Characters in C Cause Undefined Behavior?. For more information, please follow other related articles on the PHP Chinese website!