13 Beginner The Hundred
Two Identical Strings That Are Not Equal
the same seven characters, and == still disagrees
#include <iostream>
int main() {
const char* expected = "hunter2";
char typed[] = "hunter2";
std::cout << std::boolalpha;
std::cout << "typed == expected : " << (typed == expected) << '\n';
std::cout << "expected == \"hunter2\" : " << (expected == "hunter2") << '\n';
}
Run it. Which comparisons come out true?
Answer
Same text both times — and the true isn't even guaranteed.
Why¶
Neither line looks at a single character: both operands decay to const char*, so ==
asks only do these two pointers hold the same address? typed is a local array with its
own copy of the bytes, so it sits somewhere else than the literal expected points at —
false, no matter how the text reads. The second line prints true merely because GCC
kept one copy of "hunter2" and handed both expressions its address; the standard leaves
it unspecified whether identical literals share storage, so another compiler — or the
same one across two translation units — may hand you false. That accidental true is
what lets the bug survive testing: the toy check matches, and the one fed real input
rejects everything.
-Wall catches half of it. GCC flags line 9 with comparison with string literal results
in unspecified behavior (-Waddress) — Clang says the same under -Wstring-compare — but
both stay silent about typed == expected, the comparison that is reliably wrong.
The fix¶
Compare characters with std::strcmp, or hand the job to std::string, whose == really
does compare contents:
std::strcmp(typed, expected) == 0; // true — walks the characters
std::string entered = typed;
entered == expected; // true — std::string compares contents
Takeaway: == on a char* asks same address?, never same text?
Try it: g++ -std=c++17 main.cpp -o demo && ./demo