As far as i know, the NULL is actually not 0. So is there any difference in comparing a pointer with 0 or with NULL? Further what should be the correct usage. Thanks!
3 回答
The correct usage is to use NULL
: It's more readable (p = NULL
-> you know that p
is a pointer)
In C,the macro NULL is defined as an implementation-defined null pointer constant, which in C99 can be portably expressed as the integer value 0 converted implicitly or explicitly to the type void*
.
In C++ NULL is the integer literal for zero (0
or 0L
) has been traditionally preferred to represent a null pointer constant.
Compiler would implicitly convert 0
to NULL
in case of comparison with a pointer.
It is always safe to compare 0
with NULL
.
NULL is not necessarily 0 and should only be used for pointers. NULL is a macro usually defined as (void*)0 but not always.
It's a pointer to no location in memory.
There's a very good new book called Understanding And Using C Pointers. Please read that one.
Don't use it for anything but pointers.