Is "if (!pointer)" as portable as "if (pointer == NULL)" ???

Henry Spencer henry at utzoo.uucp
Thu Apr 12 04:22:39 AEST 1990

In article <656 at hades.OZ> greyham at hades.OZ (Greyham Stoney) writes:
>...What is the simplest portable method
>that can be used to detect the NULL pointer being returned?.
>	if ((buffer = malloc(50)) != NULL)
>	if (buffer = malloc(50))	/* yes, that SHOULD be =, not == */

The two are precisely synonymous.  Use of a C expression in a conditional
context always gives an implicit comparison to zero, and comparison of a
pointer to the constant zero (e.g. to NULL, properly defined to be 0) is
comparison to a null pointer.  Any compiler which produces different
code for the two is broken or very stupid.

However, the first one is a whole lot easier to read, and is less work to
type if you include the comment on the second one (which is NOT optional!).

>NULL pointer is a special case - K&R says that casting anything with a
>value 0 to a pointer yeilds a NULL pointer; so presumably casting a NULL
>pointer back to value yeilds a zero...

No.  K&R says that casting a *constant* value 0 to a pointer yields a
null pointer.  This does not generalize any further.
With features like this,      |     Henry Spencer at U of Toronto Zoology
who needs bugs?               | uunet!attcan!utzoo!henry henry at

More information about the Comp.lang.c mailing list