Search code examples
c++c-strings

Are the literals "" (empty string) and "\0" (null string) identical?


Is there any situation where the literal const char*s "" and "\0" differ, or are they identical?

Edit: As requested that an edit should be added, the answer to this question was that an additional implicit '\0' is added to "\0" which already contains an explicit '\0'. This is different from the char question which is concerned with string compairson


Solution

  • Any string literal "..." is of the type const char [N(...) + 1], where the content consists of { ..., '\0' }, ie there is always an implicit '\0' char added on the end.

    • ""const char [1] = { '\0' }

    • "\0"const char [2] = { '\0', '\0' }

    • "hi"const char [3] = { 'h', 'i', '\0' }

    • etc

    So, if you treat them as null-terminated C strings, then "" and "\0" are functionally identical, since the 1st char is '\0' ie the null terminator, thus they both have a C-string length of 0.

    But, if you take their actual allocated sizes into account, then "" and "\0" are not the same.