Why NULL is 0

Jan Wolter janc at palam.eecs.umich.edu
Wed Mar 16 07:30:59 AEST 1988


In article <124 at polygen.UUCP> pablo at polygen.uucp (Pablo Halpern) writes:
>From article <10576 at mimsy.UUCP>, by chris at mimsy.UUCP (Chris Torek):
>> 
>> Let us begin by postulating the existence of a machine and a compiler
>> for that machine.  This machine, which I will call a `Prime', or
>> sometimes `PR1ME', for obscure reasons such as the fact that it
>> exists, has two kinds of pointers.  `Character pointers', or objects
>> of type (char *), are 48 bits wide.  All other pointers, such as
>> (int *) and (double *), are 32 bits wide.
>
>     ... if I were writing a C compiler, I would choose a size for all
>pointers equal to the size of the largest possible pointer.  This would
>allow code that passed uncasted NULL to work correctly, provided NULL
>is a type as large as a pointer....

For efficiency reasons you probably don't want to get rid of the other
pointer types.  However, why not handle pointers in function calls something
like the way char's are handled in function calls?  When I pass a char to a
function, it is automatically cast to int before being passed.  Why not
automatically cast all pointer types to (char *) before passing them?  I'm
fairly sure C does guarantee that casting a pointer to a pointer to a smaller
object and back always gives you back the same pointer.  This adds slightly
to the overhead in function calls on the Prime, but the simplification of the
interface on just about every other living machine is probably worth it.
This, of course, would only be done if no function prototype is given.

One other vaguely related question:  Which of the following produce a null
pointer?

	int zero = 0;
	char *p1 = 0;             /* this is a null pointer! */
	char *p2 = zero;          /* is this a null pointer? */
	char *p3 = (char *)zero;  /* what's this? */

As I read K&R, a null pointer is only produced when a *constant* 0 is assigned
to a pointer.  When an integer is assigned to a zero, K&R seems to suggest that
a bitwise copy is done, which may not be the same thing at all.  This seems
to be the only case in C where "a=(b=c)" is not equivalent to "a=c,b=c".

While K&R says assignment is a bitwise copy, they say explicitly typecasting
an integer to a pointer gives a machine dependent result.  Thus it seems
possible that the p1, p2, and p3 could be three different pointers.  (Frankly,
the more I read on this subject, the more I think K&R didn't have their minds
entirely clear on this business either.)

				- Jan Wolter
				  janc at crim.eecs.umich.edu



More information about the Comp.lang.c mailing list