Path: utzoo!utgpu!watmath!clyde!att!osu-cis!tut.cis.ohio-state.edu!mailrus!uflorida!novavax!proxftl!twwells!bill From: bill@twwells.uucp (T. William Wells) Newsgroups: comp.lang.c Subject: Re: pointers, tests, casts Message-ID: <226@twwells.uucp> Date: 1 Dec 88 03:07:14 GMT References: <11130@dartvax.Dartmouth.EDU> <8961@smoke.BRL.MIL> <12690@steinmetz.ge.com> Reply-To: bill@twwells.UUCP (T. William Wells) Organization: None, Ft. Lauderdale Lines: 49 Summary: Expires: Sender: Followup-To: Distribution: Keywords: In article <12690@steinmetz.ge.com> davidsen@crdos1.UUCP (bill davidsen) writes: : In article <8961@smoke.BRL.MIL> gwyn@brl.arpa (Doug Gwyn (VLD/VMB)) writes: : | In article <11130@dartvax.Dartmouth.EDU> Eric.J.Bivona@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 sure that some of the new readers of : this group would not quickly grasp the meaning of your first example, : and I'm not sure about the second. I just covered this topic in a C : course I'm teaching, and I am always amazed at how easily new C : programmers are confused by shorthand form which "mean the same thing." 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. To set the record straight, these are all equivalent: if (!ptr) if (ptr == 0) if (ptr == (the_type_of_ptr)0) if (ptr == (the_type_of_ptr)NULL) If ptr is of type `void *' or `char *' then the following is also equivalent: if (ptr == NULL) --- Bill {uunet|novavax}!proxftl!twwells!bill