Suppose I have the following code:
const char str1[] = "asdasd";
const char str2[] = "asdasd";
const char* str3 = "dsadsa";
const char* str4 = "dsadsa";
if (str1 == str2)
{
cout << "str1 == str2" << endl;
}
if (str3 == str4)
{
cout << "str3 == str4" << endl;
}
The result is "str3 == str4". Why?
For C++
str3
and str4
are pointing to identical string literals ,
The compiler is allowed, but not required, to combine storage for equal or overlapping string literals. That means that identical string literals may or may not compare equal when compared by pointer.
That means whether str3 == str4
is true
or false
is unspecified , it depends on the implementation, and the one you're using gives true
.
On the other hand, str1
and str2
are independent arrays.
String literals can be used to initialize character arrays. If an array is initialized like
char str[] = "foo";
,str
will contain a copy of the string"foo"
.
So str1 == str2
is guaranteed to be false
.
String literal pooling. Compilers tend to merge identical string literals, so there's only one copy in the program. This is allowed but not required; it would be unwise to rely on this happening.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.