When attempting to concatenate string literals with character literals in C , unexpected behavior can occur. For instance:
<code class="cpp">string str = "ab" + 'c'; cout << str << endl;</code>
This code produces unpredictable output because the " " operator is not defined for combining string literals and character literals. Instead, the compiler treats the string literal as a C-style string (a const char pointer), and adds the promoted int value of the character literal to the address of the string literal. This results in undefined behavior.
To avoid this issue, explicitly convert the character literal to a string before concatenation:
<code class="cpp">std::string str = std::string("ab") + 'c';</code>
Alternatively, use concatenation to achieve the desired result:
<code class="cpp">std::string str = "ab"; str += 'c';</code>
In the second code snippet, the string object has an overloaded " " operator that performs the intended concatenation.
The above is the detailed content of How to Concatenate String Literals and Character Literals in C ?. For more information, please follow other related articles on the PHP Chinese website!