Let's define our own NULL

Doug Gwyn gwyn at brl-smoke.ARPA
Fri Jun 24 21:50:35 AEST 1988


In article <11326 at steinmetz.ge.com> davidsen at crdos1.UUCP (bill davidsen) writes:
>The original book was written before segmented archetectures were
>commonly used, ...

That's irrelevant.  The C language guarantees that null pointers are
comparable to the integer constant 0, and that assigning integer constant
0 to a pointer of any type produces a null pointer of that type.  Also
(actually as a consequence of the assignment rule), casting integer
constant 0 to a pointer type produces a null pointer constant of that
type.  The internal representation of a null pointer is unspecified; in
particular it need be neither all zero bits nor the same size as an int.
Segmented architectures could even use more than one representation for
null pointers of a given type, so long as the language rules are obeyed.

#define NULL	0
is a universally correct symbolic definition for null pointers (of
unspecified type).

Using an ANSI-conforming implementation,
#define	NULL	((void *)0)
is also guaranteed to have the same properties.  This obviously won't
work when using compilers that don't know about (void *).

You still need to cast a null pointer constant, no matter how defined,
to have the correct type when using it as a function argument, unless
there is a prototype in scope for the function (in which case the
automatic argument type coercions will take care of this for you).

It seems we go over this every few months.  Could everyone PLEASE try
to remember this next time?

P.S. In response to the original article:  No, one needn't include
<stdio.h> just to define NULL.  You can define your own, or just use 0.
If stdio is going to be used in the application anyway, there is no
real cost associated with including <stdio.h> unnecessarily, but it IS
rather silly to do so.



More information about the Comp.lang.c mailing list