In C++11 the nullptr
keyword was added as a more type safe null pointer constant, since the previous common definition of NULL
as 0 has some problems.
Why did the standards committee choose not to call the new null pointer constant NULL
, or declare that NULL
should be #define
d to nullptr
?
As I mentioned above, the general rule of thumb that I recommend is that you should start using nullptr whenever you would have used NULL in the past. As a reminder, since C++11, NULL can be either an integer literal with value zero, or a prvalue of type std::nullptr_t .
Nullptr vs NULLNULL is 0 (zero) i.e. integer constant zero with C-style typecast to void* , while nullptr is prvalue of type nullptr_t , which is an integer literal that evaluates to zero. For those of you who believe that NULL is the same i.e. (void*)0 in C and C++.
In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days. If you have to name the null pointer, call it nullptr; that's what it's called in C++11.
nullptr is a keyword that can be used at all places where NULL is expected. Like NULL, nullptr is implicitly convertible and comparable to any pointer type. Unlike NULL, it is not implicitly convertible or comparable to integral types.
Stephan T. Lavavej (member of the C++ standard committee) explained that once in a talk (55:35):
While an implementation is allowed to #define NULL nullptr
, it would break quite some uses like
int i = NULL;
and apparently there are plenty of those. So they could not force the change.
nullptr
is of pointer type , while NULL
has the tendency to be integer, and sometimes in overloaded functions, you need to be clear that you are using a pointer and not an integer - this is when nullptr
comes in handy.
So to really answer your question, NULL
and nullptr
serve two different purposes and redefining one to another will probably break a lot of things in already existent code bases.
Beside that, check this from Bjarne Stroustrup's website:
Should I use NULL or 0?
In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days. If you have to name the null pointer, call it nullptr; that's what it's called in C++11. Then, "nullptr" will be a keyword.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With