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?
const char* and char const* says that the pointer can point to a constant char and value of char pointed by this pointer cannot be changed. But we can change the value of pointer as it is not constant and it can point to another constant char. char* const says that the pointer can point to a char and value of char pointed by this pointer can be ...
NOTE: There is no difference between const char *p and char const *p as both are pointer to a const char and position of ‘*' (asterik) is also same. You cannot change the pointer p, but can change the value pointed by ptr.
Actually, char* name is not a pointer to a constant, but a pointer to a variable. You might be talking about this other question. What is the difference between char * const and const char *?
Also, compilers are required to give error messages when you try to do so. For the same reason, conversion from const char * to char* is deprecated. char* const is an immutable pointer (it cannot point to any other location) but the contents of location at which it points are mutable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With