[comp.sys.amiga.tech] NULL

ditto@cbmvax.UUCP (Michael "Ford" Ditto) (03/08/89)

This is an article about NULL pointers in the C language.  I would have
directed followups to comp.lang.c except that this is a very simple
question and people who read comp.lang.c are sick and tired of hearing
people talk about it.

In article <6445@dayton.UUCP> joe@dayton.UUCP (Joseph P. Larson) writes:
>>In article <331@wn2.sci.kun.nl> janhen@wn2.sci.kun.nl (Jan Hendrikx) writes:
>>|(!expr) means the same as (expr != 0), which is THE test to test for a 
>>|NULL pointer.
>
>Irregardless of whether this works or not, it is better style to compare
>against NULL, a value that indicates a pointer to nowhere.

As far as style, I agree aside from the fact that you have to get the
value of NULL from somewhere, and you know 0 or ((void *)0) will work
just as well.  The #defined constant NULL is in <stdio.h>; in that sense,
it is part of the Unix standard I/O library.  Many programs, especially
on the Amiga, do not and should not have *any* dependency on the standard
I/O library, and therefore will not have a "NULL" symbol defined.
(Actually it is defined in a few of the Amiga header files as well, but
that's beside the point.)

>What if address zero is a legal address?  NULL might be -1 then.  You don't
>know how some odd machine is going to work in the future.

Zero is never a legal address in the C language.  NULL should never be -1,
although the machine might store an illegal pointer as -1.  It is always
permitted (and arguably a good practice) to #define NULL 0 (or (void *)0)
in your programs; that is the only way to reliably get a legal NULL without
using <stdio.h>.  In ANSI C you can #include <stddefs.h> to get it.

>So THE test for comparing a pointer against NULL is to compare it against
>NULL, not to depend on what NULL's value might be.  !expr or expr == 0
>works, but that is simply because on most machines, NULL is going to be
>zero.

No, it works because that is the specification of the C language.  The
only legal, portable, reliable way to test for a null pointer is to compare
it against zero, preferably cast into an appropriate type.  (!ptr) is a
very good way to do this, and it's arguably slightly better than (ptr!=0)
because the latter is comparing two objects of different types, relying
on the (guarranteed) recognition by the compiler of the special case of
comparing a pointer against the integer constant zero.  (ptr!=(void*)0) is
good on compilers that take it.  ANSI C (draft) says the compiler-vendor-
provided value of NULL can be 0, 0L, or ((void *)0).  The latter is best
because it will always be "pointer-sized" regardless of whether ints or
longs are the same size as pointers.
-- 
					-=] Ford [=-

"The number of Unix installations	(In Real Life:  Mike Ditto)
has grown to 10, with more expected."	ford@kenobi.cts.com
- The Unix Programmer's Manual,		...!sdcsvax!crash!kenobi!ford
  2nd Edition, June, 1972.		ditto@cbmvax.commodore.com