Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the comparison between const char[] and const char* different?

Tags:

c++

c

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?

like image 832
DickHunter Avatar asked Jun 22 '19 03:06

DickHunter


People also ask

What is the difference between Char* and char* const?

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 ...

What is the difference between const char *p and const *P?

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.

Is char* a pointer to a constant or variable?

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 *?

Why is conversion from const char * to char* deprecated?

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.


2 Answers

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.

like image 184
songyuanyao Avatar answered Sep 28 '22 17:09

songyuanyao


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.

like image 29
Igor Tandetnik Avatar answered Sep 28 '22 15:09

Igor Tandetnik