Home / Articles / Null Pointer
Null Pointer
Null Pointer
Consider the following code:
int x = 0;
if (x == NULL)
printf("God is healing us");
The code will compile and run, but the ANSI C standard has given a different meaning to NULL. It is reserved for pointer operations, which is why it is defined as (void *)(0).
Using NULL with a non-pointer variable like int x conflates two distinct concepts: the integer value zero and the null pointer constant. This causes confusion and potential warnings from conforming compilers, because NULL is a pointer constant and comparing it directly to an integer mixes types.
The correct use of NULL is exclusively with pointers:
int *ptr = NULL; /* Correct: NULL used as a null pointer constant */
if (ptr == NULL)
printf("Pointer is null\n");
When checking whether an integer is zero, use the literal 0:
int x = 0;
if (x == 0)
printf("x is zero\n");
The ANSI C standard defines NULL in <stddef.h> (and several other standard headers). Its exact definition is implementation-defined but must be a null pointer constant — typically (void *)0 on C compilers or simply 0 on C++ compilers.