pointers, tests, casts

Doug Gwyn gwyn at smoke.BRL.MIL
Wed Nov 23 16:09:34 AEST 1988


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.

Explicit casting of 0 (or NULL, defined in several headers) is required
only when the compiler could mistake the 0 for an int constant rather
than the intended null pointer constant.  The main place this can occur
is in the arguments to a function when no prototype is in scope, e.g.
	execl( "/bin/sh", "-sh", "-i", 0 );
(This one is even worse since it's a variable-argument function, so not
even a prototype would help.)  The bug typified by this is seen in a
LOT of code ("well it worked on MY machine!").



More information about the Comp.lang.c mailing list