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

Greyham Stoney greyham at hades.OZ
Wed Apr 11 10:47:02 AEST 1990


When using functions that return pointers, it's pretty common to return a
NULL pointer when something fails. What is the simplest portable method
that can be used to detect the NULL pointer being returned?.

For example you can compare it with NULL:
	char *buffer;

	if ((buffer = malloc(50)) != NULL)
		use(buffer);
	else
		exit(1);

But can you also just do an aritmetic check on the cast value of the pointer?:
	char *buffer;

	if (buffer = malloc(50))	/* yes, that SHOULD be =, not == */
		use(buffer);
	else
		exit(1);

Now that second one looks much simpler to me, but is it as portable?. Now
you might say "Ah, but the value of NULL is not necessarily zero!". But a
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. The actual value of the NULL pointer is
irrelevant since the implicit cast will convert to and from it.

Is this correct?. Can I just do:
	if (buffer) free(buffer)
And stuff like that?.
							Greyham.
-- 
/*  Greyham Stoney:                            Australia: (02) 428 6476  *
 *     greyham at hades.oz  - Ausonics Pty Ltd, Lane Cove, Sydney, Oz.      *
 *          "BUT THAT'S JUST A BUTTON ON A STRING, BASICLY!!!"           */



More information about the Comp.lang.c mailing list