Can someone explain to me why txt3, txt4
and txt4, txt5
are not equal?
Why does (txt3 == txt4)
and (txt5 == txt6)
give false?
#include <iostream>
#include <string>
using namespace std;
int main()
{
string txt1("EL020GM");
string txt2("EL020GM");
char txt3[] = "EL020GM";
char txt4[] = "EL020GM";
char * txt5 = &txt3[0];
char * txt6 = &txt4[0];
const char * txt7 = "EL020GM";
const char * txt8 = "EL020GM";
if(txt1 == txt2) { std::cout << "yes\n"; } else{ std::cout << "no\n"; }
if(txt3 == txt4) { std::cout << "yes\n"; } else{ std::cout << "no\n"; }
if(txt5 == txt6) { std::cout << "yes\n"; } else{ std::cout << "no\n"; }
if(txt7 == txt8) { std::cout << "yes\n"; } else{ std::cout << "no\n"; }
return 0;
}
std::cout << (txt1 == txt2 ? "yes" : "no") << '\n';
But like the answer says, your Boolean expression needs fixing.txt7
andtxt8
equals is that they are declaredconst
, hence immutable. If they are assigned the same string, the compiler knows it can safely make them point to the same place, unliketxt3
andtxt4
which can change over time, hence needing each their own space in memory.bool operator== (const std::string& left, const std::string& right) { ... }
likely exists (or something similar), but I doubt, there existsbool operator==(const std::string& left, const char* right) { return false; }
or similar or more generic. C++ has its flaws and there is no benefit in giving glorified excuses for such pathological situations.