Home > Backend Development > C++ > body text

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

DDD
Release: 2024-10-25 05:37:29
Original
188 people have browsed it

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>
Copy after login

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>
Copy after login

Alternatively, we can use concatenation:

<code class="cpp">string str = "ab";
str += 'c';</code>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!