pointers, tests, casts

shirono at hcx3.SSD.HARRIS.COM shirono at hcx3.SSD.HARRIS.COM
Fri Dec 2 01:33:00 AEST 1988


In comp.lang.c, bill at twwells.uucp writes:
> In article <12690 at steinmetz.ge.com> davidsen at crdos1.UUCP (bill davidsen) writes:
> : In article <8961 at smoke.BRL.MIL> gwyn at brl.arpa (Doug Gwyn (VLD/VMB) <gwyn>) writes:
> : | In article <11130 at dartvax.Dartmouth.EDU> Eric.J.Bivona at Dartmouth.EDU writes:
> : | >I have a question about tests on pointers, ...
> : |
> : |     if ( !ptr )
> : | and
> : |     if ( ptr == 0 )
> : | are both perfectly valid ways to test for a null pointer.  You can
> : | explicitly cast the 0 to the proper type, but it's not necessary.
> :
> : Doug, as usual you are correct, but I have to point out that
> :       if (ptr == NULL)
> : also works, usually generates the same code, and gives a much better
> : idea of what the code is doing.
>
> I'm afraid that you've just contributed to the confusion.  In the
> material you quoted, the type of `ptr' is not specified. That being
> the case,
> 
> 	if (ptr == 0)
> 
> is not equivalent to
> 
> 	if (ptr == NULL)
> 
> They are only equivalent if the type of ptr is `void *' or `char *'.
> Otherwise, there are are implementations, those defining NULL as
> (char *)0, which will give an error on the latter statement.

WRONG.

I'm afraid you may have lost some context, but the original poster
(Eric.J.Bivona at Dartmouth.EDU) asked his question in the framework of ANSI
C.  Doug Gwyn's answer is (of course) correct, and Bill Davidsen's remark,
while reflecting an opinion, is correct in implementation (i.e,
	if (ptr == NULL)
is correct).

Even in the K&R1 days, the only valid definition of NULL has been

#define NULL 0

Any other implies a broken compiler/compilation-environment, and should be
discarded.

--Roberto
______________________________________________________________________________
                               ||   Internet: shirono at ssd.harris.com
     Roberto Shironoshita      ||
      Harris Corporation       ||             ...!novavax---\
   Computer Systems Division   ||   UUCP:     ...!uunet-------!hcx1!shirono
                               ||             ...!mit-eddie-/
------------------------------------------------------------------------------
DISCLAIMER: The opinions expressed here are my own; they in no way reflect the
            opinion or policies of Harris Corporation.



More information about the Comp.lang.c mailing list