10

The C++ nullptr is of the type std::nullptr_t.

Why does a program like

int main() {
 int* ptr = nullptr;
}

still work, although it doesn't include any STL library?

10
  • 13
    Because nullptr is a keyword of the language much like int. Commented Aug 22, 2016 at 13:22
  • What library do you believe would need including here? Commented Aug 22, 2016 at 13:22
  • 4
    @RobertHönig The C++ nullptr is of the type std::nullptr_t. Actually its the other way around, from cppreference: typedef decltype(nullptr) nullptr_t;
    – Borgleader
    Commented Aug 22, 2016 at 13:25
  • 1
    @RobertHönig : <iostream.h> and the STL were two distinct libraries that both were included in Standard C++. The third major library included in C++ is the Standard Library from C. And std::nullptr_t came from neither; it's a C++11 invention.
    – MSalters
    Commented Aug 22, 2016 at 13:29
  • 1
    <iostream.h> was present in some (early) drafts of the C++ standard, but was never in a ratified standard.
    – Peter
    Commented Aug 22, 2016 at 14:13

1 Answer 1

16

In C++11 they wanted to add a keyword to replace the macro NULL (which is basically defined as #define NULL 0), both because it is a core concept, and because of some annoying bugs you get when you are forced to use 0 as your null pointer constant.

A number of keywords where proposed. Large codebases where searched to ensure that the keyword was not in use, and that it still described what they wanted (a null pointer constant).

nullptr was found to be sufficiently rare and evocative enough.

The type of nullptr was not given a keyword name by default, because that wasn't required for most programs. You can get it via decltype(nullptr) or including a std header and using std::nullptr_t.

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