Concatenating String Literals with Strings
In C , the operator can be used to concatenate strings and string literals. However, there are limitations to this functionality that can lead to confusion.
In the question, the author attempts to concatenate the string literals "Hello", ",world", and "!" in two different ways. The first example:
const string hello = "Hello";
const string message = hello ",world" "!";
In this case, the code compiles and runs successfully. This is because the first operand to the operator is a string object (hello), so the compiler treats this as a concatenation of a string and two string literals.
However, the second example:
const string exclam = "!";
const string message = "Hello" ",world" exclam;
fails to compile. This is because the leftmost operator is attempting to concatenate two string literals, which is not allowed. The compiler interprets this code as:
const string message = (("Hello" ",world") exclam);
and the first concatenation is trying to add two pointers (const char* literals) together.
To resolve this issue, the code should either:
Make one of the first two strings being concatenated a string object:
const string message = string("Hello") ",world" exclam;
Use parentheses to force the second to be evaluated first:
const string message = "Hello" (",world" exclam);
The reason you can't concatenate two string literals using is because string literals are stored as arrays of characters, which can't be directly added together. When you use a string literal in most contexts, it's converted to a pointer to its initial element, which is not a valid operand for the operator.
Therefore, it's important to remember that only one of the two leftmost operands in a concatenation expression can be a string literal. String literals can, however, be concatenated by placing them next to each other, as in:
"Hello" ",world"
"Hello,world"
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3