[comp.lang.c] pointer checking

jesup@pawl20.pawl.rpi.edu (Randell E. Jesup) (02/17/88)

In article <228@gandalf.littlei.UUCP> martin@littlei.UUCP (martin) writes:
>I do not want to start another net wars, but I am tired of seeing
>people write programs that are non-portable between C compilers.

>If you look at the source you will see that the authors blatenly
>compaired pointers to zero without thinking what happens if
>sizeof(ptr) != sizeof(int).  I know that C does not gripe if
>you do something like this, but can't people program better?

>char *ptr;

>if (ptr) {		/* WRONG !!!!!! */
>    do something
>}

>if (ptr != (char *)NULL) { 	/* RIGHT !!!!!! */
>    do something
>}

	Excuse me, nothing seems wrong to me with "if (ptr)".  From K&R,
page 52:
	"Since an if simply tests the numeric value of an expression, certain
coding shortcuts are possible.  The most obvious is writing
		if (expression)
instead of
		if (expression != 0)"

Also, from K&R page 192:
	"... it is guaranteed that assignment of the constant 0 to a pointer
will produce a null pointer distinguishable from a pointer to any object."

So, NULL must be equivalent to 0.

I will note that there are a couple of broken compilers out there that MIGHT
get this wrong.  However, it is most certainly absolutely correct C.

You are right, however, to note that there are far too many programs that
assume sizeof(int) == sizeof(pointer), and that this breaks things (or assume
that sizeof(int) == sizeof(long))!

     //	Randell Jesup			      Lunge Software Development
    //	Dedicated Amiga Programmer            13 Frear Ave, Troy, NY 12180
 \\//	beowulf!lunge!jesup@steinmetz.UUCP    (518) 272-2942
  \/    (uunet!steinmetz!beowulf!lunge!jesup) BIX: rjesup