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

thomas.j.roberts tjr at cbnewsc.ATT.COM
Thu Apr 12 00:22:18 AEST 1990


>From article <1461 at tkou02.enet.dec.com>, by diamond at tkou02.enet.dec.com (diamond at tkovoa):
> In article <656 at hades.OZ> greyham at hades.OZ (Greyham Stoney) writes:
>>	if (buffer = malloc(50))	/* yes, that SHOULD be =, not == */
> 
> Yes it is portable, just not readable...

But beware. In modern compilers (e.g. TURBO C), this will generate
a warning (HURRAY!) about a questionable assignment in a conditional context.

Avoid the warning with either:
	if( (buffer=malloc(50)) != 0) [...]
or
	if( !!(buffer=malloc(50)) ) [...]

Personally, I either invert the if:
	buffer = malloc(50);
	if(!buffer) goto error;		/* Yes, it is usually a goto, for there
					   are often dozens of error legs */
Or, more often, supply my own error-checking routine to malloc:
	extern void *emalloc(size_t n_bytes);
	buffer = emalloc(50);	/* emalloc() bombs on malloc() failure */

Tom Roberts
att!ihlpl!tjrob



More information about the Comp.lang.c mailing list