0

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:

  1. Why is that so?

  2. How is operator== implemented? Does it check every single char, or does it ignore '\0'?

  3. 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 got 1. Is this undefined behavior?

4
  • Just read the source code and/or the spec (e.g. cppreference.com). BTW: That also explains the "not null-terminated". However, read that carefully, because "not null-terminated" means that null is a regular, non-terminating element value. Apr 25, 2020 at 7:32
  • 1
    "\0" is a C-style string of zero length and gets converted to an empty std::string.
    – molbdnilo
    Apr 25, 2020 at 7:38
  • 1
    "\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? Apr 25, 2020 at 7:40
  • You might also compare "he\0ho"s (literals string suffix) to std::string("he\0ho"). the latter std:string doesn't contain o.
    – Jarod42
    Apr 25, 2020 at 8:12

1 Answer 1

1

'\0' is a single char with an ordinal value of 0. operator+=(char) adds any char to the string without regard to its value. Comparing y.size() before and after the append , you will see that the size increases by 1.

"\0" is a string literal, a const char[2] containing two null characters, one explicit by you and one implicit by the compiler. When treated as a C-style null-terminated string by operator+=(const char*), its logical length stops at the first null character, thus its length is effectively 0. Comparing y.size() before and after the append, you will see that the size does not change.

operator== takes size() into account. Two strings of different sizes will return false. Two strings of same size will compare all of their chars, including embedded null characters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.