NULL pointers

John Bruner jdb at mordor.ARPA
Sat Nov 22 04:13:50 AEST 1986


>#ifdef HASVOID
>#define NULL ((void *)0)
>#else
>#define NULL 0L
>#endif

There is no need to define NULL to be anything other than 0.
Defining NULL as (void *)0 or 0L to avoid casts in function calls
detracts from portability.

In all contexts except arguments to functions, the integer constant 0
will be converted to the appropriate representation for a nil pointer.
This may mean that it is widened (e.g. on a 68000 whose C compiler uses
16-bit "int"s), or there may be some other conversion.

When a nil pointer is to be passed as an argument to a function, NULL
must be cast to the appropriate type.  (This assumes that there is no
function prototype, which is true for the vast majority of C compilers
available today.)  It is not sufficient to pass (void *)0, because
there is no guarantee that pointers to different-sized objects have
the same representation.

It is worse to use 0L when a pointer argument to a function is expected.
There are implementations [e.g. a PDP-11 running version 7] where
sizeof(anything *) < sizeof(long).  The only way to ensure that the
correct amount of information, in the correct format, is passed, is
to cast the argument when the function is called.
-- 
  John Bruner (S-1 Project, Lawrence Livermore National Laboratory)
  MILNET: jdb at mordor [jdb at s1-c.ARPA]	(415) 422-0758
  UUCP: ...!ucbvax!decwrl!mordor!jdb 	...!seismo!mordor!jdb



More information about the Comp.lang.c mailing list