Search code examples
c++pointerscharnullptr

Why do we have nullptr but not nullchar?


My understanding - and I'm sure I'm about to learn - is that nullptr was added to C++ to formalise the convention that a zero value for a pointer means the pointer does not point to a valid object. Is there a case for (or against) adding a corresponding nullchar to formalise the convention that a zero value for a char means the char is not a valid character but is instead the terminator of a string? I can see a few things which the two cases have in common:

Type safety: 0 can have several different types, so it's easy to mistakenly assign a non-pointer variable to zero instead of the pointer variable you meant to. It's also easy to call the wrong overloaded function if you get it just right. Having a special and strongly-typed value prevents this kind of mistake, and this could be true for char types as well.

Expressiveness: Assigning a variable to be nullptr makes it clear to the reader that the variable is a pointer (because only a pointer can be assigned to that value) and that it points to no object. Assigning a char to nullchar would add the same kind of clarity and readability.

There's more, but I'm sure you get the idea. So why do we have nullptr but not nullchar?


Solution

  • No, because there's not as much reason to, really. nullptr was added to remove the need of the NULL macro, which in C is defined as something like (void*)0. In C, void* is implicitly convertible to any pointer type, so this would work. However, this is not true in C++, which removed this implicit convertibility (but not its inverse, from any pointer type to void*), to increase type safety. However, C++ still wanted to have an easy way to make any pointer a null pointer, which is why nullptr_t was introduced, which is implicitly convertible to any pointer type like void* once was, BUT can only contain the null pointer value, nullptr. In C++ you can represent a null character with '\0' with no type ambiguity or unnecessary explicit conversions, so there's no reason for a nullchar value, which would also take up another valuable reserved identifier (standard committee really likes to preserve those.)