In the following code:
string x="test";
string y="test";
y += '\0';
cout << (x==y) << endl;
prints:
0
But, the same code with a slight change:
string x="test";
string y="test";
y += "\0";
cout << (x==y) << endl;
prints:
1
The questions are:
Why is that so?
How is
operator==
implemented? Does it check every single char, or does it ignore'\0'
?I've read that C++ strings are not null-terminated. In a check I did about the existence of the
'\0'
char in a normal string literal, I got1
. Is this undefined behavior?
"\0"
is a C-style string of zero length and gets converted to an emptystd::string
."\0"
-- The+
sees that this is a C-string literal and will thus search for the first null byte for termination. Guess where the first null byte is?"he\0ho"s
(literals string suffix) tostd::string("he\0ho")
. the latterstd:string
doesn't containo
.