10

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

4

2 Answers 2

43

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.

1
  • 10
    This is also a good example of the difference between "equal" and "equivalent", something you will encounter more often and it is good to know these words are not the same. Commented Mar 1 at 8:09
3

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.

1
  • 1
    For those wondering: I skipped some explanation because other answers exist. I wanted to get some code up to make the difference more than theoretical.
    – JaMiT
    Commented Feb 28 at 22:32

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.