Why does `equal` work for const char * in C ++?
The codes are like this: it outputs 1
:
int main(int argc, char *argv[])
{
vector <const char*> vec = {"nima","123"};
vector <const char*> vec2 = {"nima","123"};
auto result = equal(vec.cbegin(), vec.cend(), vec2.cbegin());
cout << result << endl;
return 0;
}
I knew I could check if two c-style strings are equal only with strcmp
(because it is char*
not an object as I understood it). But there equal
is a function from <algorithm>
. Does it overload the operator ==
so that it can check equality of two char*
?
@Damon says they are equal to how merges the same string literal to the same address as I understand it. However, when I tried char*
with different addresses, it still gives me the same result:
int main(int argc, char *argv[])
{
char* k = "123";
char* b = "123";
vector <const char*> vec = {"nima"};
vector <const char*> vec2 = {"nima"};
cout << &k << endl;
cout << &b << endl;
vec.push_back(k);
vec2.push_back(b);
auto result = equal(vec.cbegin(), vec.cend(), vec2.cbegin());
cout << result << endl;
return 0;
}
Result:
0x7fff5f73b370 0x7fff5f73b368 1
source to share
What is probably happening here is that the compiler / linker concatenates four string literals, two of which are identical to the two literals. Therefore both "nima"
and both "123"
have the same address.
You store the addresses in a vector and compare them ( operator==
by address). Since the addresses are the same, the comparison is equal.
Please note that this is accidential . It only works for two reasons:
- Strings are literals (that is, not some strings read, for example
stdin
). - Compiler allowed, but not required to concatenate identical literals (whether that happens or not).
This can lead to two situations in which you get a funny surprise (not so funny if you have to figure out why it suddenly doesn't work when it was "running" all the time), or when using a different compiler, or even the same compiler with different optimization settings, or when you assign non-liberal strings.
source to share