Home > Backend Development > C++ > How to Concatenate String Literals and Character Literals in C ?

How to Concatenate String Literals and Character Literals in C ?

DDD
Release: 2024-10-25 09:05:02
Original
452 people have browsed it

How to Concatenate String Literals and Character Literals in C  ?

String Literals and Character Literals in C

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

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

Alternatively, use concatenation to achieve the desired result:

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

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!

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