pointers, tests, casts

T. William Wells bill at twwells.uucp
Thu Dec 1 13:07:14 AEST 1988


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 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



More information about the Comp.lang.c mailing list