Null revisited (briefly)

William E. Davidsen Jr davidsen at steinmetz.ge.com
Fri Feb 3 01:06:24 AEST 1989


So many people have misread my last posting that I feel it is necessary
to restate what I said more clearly. When I corrected the person who
said any compiler which didn't define NULL to be zero was broken, and
quoted dpAns, I was not trying in any way to convince anyone that NULL
*must* be cast to a pointer type, only that it is valid to do so.

A portable program will not assume that it is an int or a pointer, but
will use it in ways which do not make any assumptions as to type. I
offer these ideas on avoiding problems, with *no* claim that they cover
all cases:
	1) If you mean zero, use zero
	2) NULL with either type of declaration works when assigned
	   to a pointer or compared with a pointer. ie. "foo = NULL"
	   or "if (foo == NULL)" should work for NULL defined as int
	   or pointer.
	3) NULL used as an argument to a procedure or macro should be
	   cast. The macro may not use it in a way which requires
	   casting, but it is better to be consistent.

About end of string:

  Some peopke put a zero in a char using NULL, such as "ffoA[n]=NULL".
I think this is portable for either type, but I have seen compilers
which warn about type conversion is NULL is a pointer. To avoid this I
have defined an EOS (end of string) macro which does not produce the
warnings, at least on compilers I've tried.

	#define EOS	((unsigned char) 0)

  I don't think this will work any better than NULL, but it certainly is
quieter.

  Hopefully this will clarify what I originally meant, so that the
people who want to disagree can at least do so based on what I meant and
not what they thought I said.

  Several people wrote and asked why anyone would define NULL as a
pointer in their stdio.h file. Because there is a lot of code which
uses uncast NULL as a procedure argument, it is important that it be a
pointer type where the size or form of an int is not the same as that
of a pointer. There is no way to solve all portability problems if
pointers to diferent types have diferent forms, but for implementations
in which all pointers have the same form, a pointer NULL can save the
users trouble porting code which was written without adequate attention
to portability.

-- 
	bill davidsen		(wedu at ge-crd.arpa)
  {uunet | philabs}!steinmetz!crdos1!davidsen
"Stupidity, like virtue, is its own reward" -me



More information about the Comp.lang.c mailing list