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

How to Concatenate String Literals and Character Literals in C ?

DDD
DDDOriginal
2024-10-25 09:05:02326browse

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>

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!

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