asimes
asimes

Reputation: 6080

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

Upvotes: 12

Views: 1077

Answers (3)

Remy Lebeau
Remy Lebeau

Reputation: 597885

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.

Upvotes: 41

JaMiT
JaMiT

Reputation: 17063

For a somewhat contrived example where they differ, define a function taking a reference to an array as an argument. (This is not common outside function templates, hence I call it "contrived".)

#include <iostream>

void foo(const char (&two_chars)[2]) {
    std::cout << "1:" << two_chars[0] << '\n';
    std::cout << "2:" << two_chars[1] << '\n';
}

Trying to invoke foo("") fails because of a type mismatch (const char [1] versus const char [2]), but foo("\0") succeeds. And for what it's worth, foo("\0\0") also fails as its array size is 3.

Upvotes: 3

Kai
Kai

Reputation: 277

sizeof("") -> 1

sizeof("\0") -> 2

Upvotes: -1

Related Questions