[net.unix-wizards] NULL as a pointer value...

ark@rabbit.UUCP (Andrew Koenig) (06/30/84)

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.

andrew@hwcs.UUCP (Andrew Stewart) (07/12/84)

I am in the depths of yet another discussion about types in C, and I'm
looking for comments, etc. on this:
	Which is better coding style,
		char	*x; .....  x = (char *)NULL;
	or
		char	*x; .....  x = NULL;
I am unhappy about NULL as a polymorphic pointer type, since it's actually
just a macro, *but* is that relevant? K&R say (can't recall where) that
NULL is an illegal pointer for *any* object, and yet
		x = NULL; .... y = *x;
will not blow up, unless you do clever things with page 0.
And what about
		return((char *)NULL);
	or
		return(NULL);

This may have been aired before - if so, forgive me - but it seems
rather interesting.

----------------
"Not a bug, a feature! It's documented, dash it!"
	Andrew Stewart.
	...!vax135!ukc!edcaad!hwcs!andrew	(UUCP)