This question already has an answer here:
As mentioned in the question, I have been using NULL and false(in C++) interchangeably with 0 or 0x0 and so on. I was curious to know if they held any special meaning other than being synonyms of 0.
This question already has an answer here:
As mentioned in the question, I have been using NULL and false(in C++) interchangeably with 0 or 0x0 and so on. I was curious to know if they held any special meaning other than being synonyms of 0.
for some platforms
NULL
is not0x0
From Is NULL in C required/defined to be zero? :
NULL
is guaranteed to be zero, perhaps casted to(void *)
1.C99, §6.3.2.3, ¶3
And note 55 says:
Notice that, because of how the rules for null pointers are formulated, the value you use to assign/compare null pointers is guaranteed to be zero, but the bit pattern actually stored inside the pointer can be any other thing (but AFAIK only few very esoteric platforms exploited this fact, and this should not be a problem anyway since to "see" the underlying bit pattern you should go into UB-land anyway).
So, as far as the standard is concerned, the two forms are equivalent (
!ptr
is equivalent toptr==0
due to §6.5.3.3 ¶5, andptr==0
is equivalent toptr==NULL
);if(!ptr)
is also quite idiomatic.That being said, I usually write explicitly
if(ptr==NULL)
instead ofif(!ptr)
to make it extra clear that I'm checking a pointer for nullity instead of some boolean value.void *
cast cannot be present due to the stricter implicit casting rules that would make the usage of suchNULL
cumbersome (you would have to explicitly convert it to the compared pointer's type every time).Generally in
C++
you shouldn't useNULL
. InC
,NULL
is a macro for(void*)0
, whereas inC++
you should use0
instead ofNULL
. But you can't usefalse
instead of0
for pointers! Apart from that, they are actually the same, sometimes causing confusion.This is why in
C++11
anullptr
was defined as use for pointers.NULL has got wide meaning in pointers. Most probably a pointer declared as NULL is something that cannot be referenced but just can be assigned something. whereas 0 or 0x0 can be the value of the pointer which can be both referenced and assigned.
In C and historic C++,
NULL
has to be a zero-valued integer constant, typically0
. I think that C can include an explicit cast tovoid*
, but C++ can't since that language doesn't allow implicit conversion fromvoid*
to other pointer types.In modern C++, it could be either
nullptr
instead.In either case, any zero-valued integer constant (including oddities such as
'\0'
andfalse
) is convertible to a null pointer value.from linux kernel stddef.h
So it is not exactly
false
even though this post claims it is
NULL
,0x0
andfalse
are almost the same.Well, NULL may not be zero, it just usually is. It's dependant on your platform - here are some nasty examples of non-zero NULL machines.