You should be using nullptr not NULL in modern C++. It has better type safety.
It is also good understand what is going on, in C and C++ when the value 0 is used in a pointer context when the compiler is required to transform that value to the null pointer representation of the underlying platform. Note that for a large number of platforms the null pointer representation is the value 0 but it does not have to be. The macro NULL was introduced into C (and carried over into C++) as a shortcut so that programmers could make it obvious in the code when they were using the null pointer rather than the value 0.
In C NULL was defined as
This works because in C you can implicitly convert between most integer types and pointers at their base level (certainly in C) are just a integer type with some additional semantics about how you interpret them.
The along came C++ with its improved type safety, pointers stopped being related to integers and also stopped being related to each other if they pointed to different things so this code
-
void *x = 0;
-
int * y = x;
-
compiles fine in C (to this day) but causes an error in C++ at the second line because you can't assign
void *
to
int *
.
So they changed the definition of NULL to
and because the compiler is require to convert the value 0 used in a pointer context to the null pointer representation for the platform that worked.
But now NULL is just the value 0 which is valid in many contexts so
-
void *x = NULL;
-
int y = NULL;
-
double z = NULL;
-
All compile (although modern compilers tend to look for NULL and issue warnings) because
-
void *x = 0;
-
int y = 0;
-
double z = 0;
-
Are all valid statements.
The C++ community felt it could do better and came up with the keyword/type nullptr. This indicates to the compiler that you are intending to use a nullptr, the standard requires the compiler to implicitly convert nullptr to the pointer type required for the current context so
-
void *x = nullptr;
-
int *y = nullptr;
-
double *z = nullptr;
-
All compile but
-
int *y = nullptr;
-
double *z = nullptr;
-
-
int v = nullptr;
-
z = y;
-
issues errors on lines 4 and 5.
So were does all this leave us?
Well if you want to set an integer to 0 then use 0, not NULL NULL is for pointers and an integer is never NULL semantically as the context of NULL means has no valid value and 0 is a valid value for an integer; similarly for floating point types use 0.0.
If you want to set a pointer to the null pointer then use nullptr, it has better type safety and is in all ways better than NULL.
But also do not consider the value of the null pointer, do not think I am setting the pointer to 0 because depending on the platform you may not be doing that always think I am setting the pointer to the null pointer representation (or just null pointer) without worrying about what that value actually is.