In the early days of C++ when it was bolted on top of C, you could not use NULL as it was defined as (void*)0
. You could not assign NULL to any pointer other than void*
, which made it kind of useless. Back in those days, it was accepted that you used 0
(zero) for null pointers.
To this day, I have continued to use zero as a null pointer but those around me insist on using NULL
. I personally do not see any benefit to giving a name (NULL
) to an existing value - and since I also like to test pointers as truth values:
if (p && !q)
do_something();
then using zero makes more sense (as in if you use NULL
, you cannot logically use p && !q
- you need to explicitly compare against NULL
, unless you assume NULL
is zero, in which case why use NULL
).
Is there any objective reason to prefer zero over NULL (or vice versa), or is all just personal preference?
Edit: I should add (and meant to originally say) that with RAII and exceptions, I rarely use zero/NULL pointers, but sometimes you do need them still.
I think the standard guarantees that NULL == 0, so you can do either. I prefer NULL because it documents your intent.
I would say history has spoken and those who argued in favour of using 0 (zero) were wrong (including Bjarne Stroustrup). The arguments in favour of 0 were mostly aesthetics and "personal preference".
After the creation of C++11, with its new nullptr type, some compilers have started complaining (with default parameters) about passing 0 to functions with pointer arguments, because 0 is not a pointer.
If the code had been written using NULL, a simple search and replace could have been performed through the codebase to make it nullptr instead. If you are stuck with code written using the choice of 0 as a pointer it is far more tedious to update it.
And if you have to write new code right now to the C++03 standard (and can't use nullptr), you really should just use NULL. It'll make it much easier for you to update in the future.
I try to avoid the whole question by using C++ references where possible. Rather than
you might often be able to write
Of course, this doesn't always work; but null pointers can be overused.
If I recall correctly NULL is defined differently in the headers that I have used. For C it is defined as (void*)0, and for C++ it's defines as just 0. The code looked something like:
Personally I still use the NULL value to represent null pointers, it makes it explicit that you're using a pointer rather than some integral type. Yes internally the NULL value is still 0 but it isn't represented as such.
Additionally I don't rely on the automatic conversion of integers to boolean values but explicitly compare them.
For example prefer to use:
rather than:
Suffice to say that this is all remedied in C++11 where one can simply use
nullptr
instead ofNULL
, and alsonullptr_t
that is the type of anullptr
.