In his book "Accelerated C ," Koenig introduces the concept of using the ' ' operator to concatenate string literals and objects. While this may seem straightforward, there are subtle nuances that can lead to unexpected results.
Consider the following two examples:
const string hello = "Hello";
const string message = hello ",world" "!";
const string exclam = "!";
const string message = "Hello" ",world" exclam;
The first example successfully concatenates the three strings. However, the second example fails.
To understand the discrepancy, we must consider the associativity of the ' ' operator. The ' ' operator is left-to-right associative, meaning it evaluates from left to right. This can lead to unexpected behavior if not taken into account.
In the second example, the expression can be parenthesized as:
const string message = ("Hello" ",world") exclam;
As you can see, the two string literals, "Hello" and ",world," are concatenated first. This results in a string literal, which cannot be further concatenated with the string object "exclam."
There are several ways to resolve this issue:
const string message = string("Hello") ",world" exclam;
const string message = "Hello" (",world" exclam);
The ' ' operator is designed to concatenate string objects, not string literals. A string literal is an array of characters, and when used in an expression, it is converted to a pointer to its initial element. Adding two pointers, as in the case of concatenating string literals, is not allowed in C .
While you cannot concatenate string literals using the ' ' operator, you can combine them by placing them side-by-side:
"Hello" ",world"
This is equivalent to:
"Hello,world"
This is useful for breaking up long string literals onto multiple lines.
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