Newsgroups: comp.lang.c Path: utzoo!henry From: henry@utzoo.uucp (Henry Spencer) Subject: Re: Is "if (!pointer)" as portable as "if (pointer == NULL)" ??? Message-ID: <1990Apr11.182239.8435@utzoo.uucp> Organization: U of Toronto Zoology References: <656@hades.OZ> Date: Wed, 11 Apr 90 18:22:39 GMT In article <656@hades.OZ> greyham@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@zoo.toronto.edu