NULL as a pointer value...
Andrew Koenig
ark at rabbit.UUCP
Sun Jul 1 00:58:08 AEST 1984
Strictly speaking, NULL is not part of the language, but is
defined as the constant 0 in <stdio.h> for convenience.
The language guarantees the following things about pointers
and integers. The numbers in brackets are sections of the
C reference manual in K&R:
A pointer may be converted to any of the
integral types large enough to hold it. [14.4]
An object of integral type may be explicitly
converted to a pointer. The mapping always
carries an integer converted from a pointer
back to the same pointer, but is otherwise
machine dependent. [14.4]
It is guaranteed that the assignment of the
constant 0 to a pointer will produce a null
pointer distinguishable from a pointer to
any object. [7.14]
When a value is used in a context in which a value of some
other type is required, such as the right side of an assignment
or after a 'return' keyword, it is converted to that type.
Thus:
struct foo *x = NULL;
struct foo *x = 0;
struct foo *x = (struct foo *) NULL;
struct foo *x = (struct foo *) 0;
are all equivalent, and which one you use is pretty much
a matter of taste. I prefer the first one, myself.
Function arguments are not automatically converted, so
the following are NOT equivalent:
fun (NULL)
fun ((struct foo *) NULL);
Assuming that fun takes a pointer to a struct foo as an
argument, the first example is incorrect (and will in
fact blow up on machines whose pointers are bigger
than their ordinary integers).
Finally, the fact that you can reference the thing pointed
to by a NULL pointer is an artifact of your particular
implementation. There are some implementations on which
you cannot do this.
More information about the Comp.unix.wizards
mailing list