Up to now, we have seen that in C++, the null pointer is represented by the keyword nullptr while prior to the C++ 2011 standard, the value 0 was used for the null pointer.
In C, the null pointer is generally represented by the macro
#define NULL ((void *) 0)
That is, NULL is 0 cast as a general address or pointer. Now, by default, NULL is not defined; instead, you must load a library that makes such a definition. The most obvious choice is to include the standard definitions library:
#include <stddef.h>
Another library in which NULL is defined is
#include <stdio.h>
Unfortunately, if you were to try to compile the following program,
#include <stdio.h> #define NULL ((void *) 0) int main() { int *n = NULL; printf( "%p\n", n ); return 0; }
you would get a compile-time error:
$ gcc sample.c sample.c:3:0: warning: "NULL" redefined [enabled by default] #define NULL ((void *) 0) ^ In file included from /usr/include/_G_config.h:15:0, from /usr/include/libio.h:32, from /usr/include/stdio.h:74, from sample.c:1: /usr/lib/gcc/x86_64-redhat-linux/4.8.5/include/stddef.h:402:0: note: this is the location of the previous definition #define NULL ((void *)0) ^
Even though the definition is identical, the compiler will not allow repeated definitions, and therefore you may wish to hedge your definition:
#ifndef NULL #define NULL ((void *) 0) #endif
Thus, NULL will only be defined if NULL is not yet defined (ifndef is short for "if not defined").