if (p), where p is a pointer

Andrew Koenig ark at alice.UucP
Thu Sep 12 01:05:04 AEST 1985


> With all this talk about NULL pointers not necessarily being equal to 0,
> I'm no longer sure what is and isn't portable code.  An C idiom I see 
> (and write) frequently is

>	<some type> *ptr;
>	...
>	if (ptr)
>	   <statement>

> Will this work correctly on a machine where NULL is not 0?  Does it really
> need to say

>	if (ptr != NULL)

No, you don't need to say NULL explicitly.  The relevant rules are:

	1. The only integer that is guaranteed to be converted
	meaningfully to a pointer is the constant 0: this is
	guaranteed to yield a value that is distinct from any
	valid pointer and is guaranteed to compare unequal to
	any valid pointer.

	2. Since 0 is the only distinctive pointer value, it is
	usually used by convention to mark the end of a list or
	to indicate a non-existent pointer value.  This convention
	is institutionalized by defining NULL as 0 in <stdio.h>.

	3. If e is an expression, if(e) and if((e)!=0) always
	mean exactly the same thing.

Thus, if NULL is defined as 0,

	if (pointer) ...

and

	if (pointer != NULL) ...

mean the same thing and the usage is portable.  If NULL is not defined
as 0, the very definition of NULL is non-portable.



More information about the Comp.lang.c mailing list