string s;
bool b[] = {s=="", s==s.c_str(), s.c_str()==""};
sets
b[] = {true, true, false};
why is b[2]
false?
If A==B
and A==C
, should that not imply B==C
?
string s;
bool b[] = {s=="", s==s.c_str(), s.c_str()==""};
sets
b[] = {true, true, false};
why is b[2]
false?
If A==B
and A==C
, should that not imply B==C
?
In this expression
s.c_str()==""
there are compared two pointers (addresses). The first one is the pointer returned by s.c_str()
and the second one is the pointer to the first character (terminaring zero character) of the string literal ""
.
It is evident that the addresses are different (bear also in mind that the string literal has the static storage duration).
To get the expected result you should write instead
std::strcmp( s.c_str(), "" ) == 0
As for these two expressions
s==""
and
s==s.c_str()
then there are compared strings because the standard class std::string has overloaded operator == for the right operand.
© 2022 - 2025 — McMap. All rights reserved.