if (p), where p is a pointer (REAL portability)
Mike Durbin
emike at riccb.UUCP
Wed Sep 18 22:59:25 AEST 1985
> [S. Friedberg]
> > [A. Koenig]
> > No, you don't need to say NULL explicitly. The relevant rules are:
> [relevant rules elided]
> > ... the usage is portable. If NULL is not defined
> > as 0, the very definition of NULL is non-portable.
>
> I have to disagree with A. Koenig's reply. The rules he cites are
> accurate, but the conclusions are unsafe.
> Moreover, saying that NULL must be defined as zero is putting the cart
> before the horse. NULL must be defined as an invalid (char *) pointer
> and if your machine architecture wants that to be 0x555555, then that
> is what NULL should be defined as. It is coincidental and NONPORTABLE
> that NULL is usually defined as 0.
> char *p;
> if (p != 0) /* NOT PORTABLE */
> if (p != NULL) /* PORTABLE */
> NULL is NOT guaranteed to be canonical "null" pointer for any type
> other than (char *).
> struct foo *f;
> if (f != NULL) /* NOT PORTABLE */
> if (f != (struct foo *)0) /* PORTABLE */
> anytype *p;
> if (f != (anytype *)0) /* PORTABLE */
>
> NULL is defined as "(char *)0", not as "0" on any sensible system and
> if your architecture is one where null pointers of all types are zeroed
> integers, there will be NO OVERHEAD using the suggested idiom, because
> even trivial compilers will generate identical code for
> if(p) /* BAD */
> if(p != (anytype *)0) /* GOOD */
>
> Stu Friedberg {seismo, allegra}!rochester!stuart stuart at rochester
I agree with Stu Friedberg (mostly).
Just because a machine architecture allows 0 to point at a valid
address, dosn't mean that the compiler designer should allow valid data
to exist at that address.
Because all static and external variables are gaurenteed to be initialized
to 0, lets try to maintain that a pointer with a value of zero points to
nothing!
But back to agreeing with Stu.
NULL *IS* defined as (char *)0 and SHOULD only be used in comparisons
with character pointers!
if ((fp = fopen(file, "r")) == NULL) /* NOT QUITE CORRECT */
if ((fp = fopen(file, "r")) == (FILE *)0) /* BETTER */
etc.
--
unixunixunixunixunixunixunixunixunixunixunixunixunixunixunixunixunixunixunixuni
n x
i E. Mike Durbin ...!ihnp4! u
x ROCKWELL TELECOMMUNICATIONS ...!ihopa!riccb!emike n
u Downers Grove IL ...!cuuxb! i
n (312) 960-8658 x
i u
xunixunixunixunixunixunixunixunixunixunixunixunixunixunixunixunixunixunixunixun
More information about the Comp.lang.c
mailing list