Home >Backend Development >C++ >Why Does Concatenating String Literals and Characters in C Cause Undefined Behavior?

Why Does Concatenating String Literals and Characters in C Cause Undefined Behavior?

DDD
DDDOriginal
2024-10-25 05:37:29254browse

Why Does Concatenating String Literals and Characters in C   Cause Undefined Behavior?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn