use of if (!cptr) and if (cptr), where cptr is a *

Paul Canniff 2/1011 paulc at microsoft.UUCP
Wed Jul 19 07:22:45 AEST 1989


In article <10099 at mpx2.mpx.com> erik at mpx2.mpx.com (Erik Murrey) writes:
>
>I'm curious how the gods feel about testing pointers in the following
>way (by example):

The gods are busy but left me an account to answer questions
while they're away.  This may explain the apparent contradiction
between a perfect and benign deity and our imperfect world, but I
am doing the best I can.

>char	*cptr, *malloc();	/* ok, so maybe malloc is void * by now... */
>
>x()
>{
>	cptr= malloc(...);
>	if (!cptr)
>		fatal("cannot malloc");
>	...
>}
>
>Would (!sptr) break anywhere?  Should it be discouraged?

It will break if NULL != 0.  This is rare in my experience.  In fact
so rare that most programs would break in such an environment.  Besides
such obvious problems as the above code, there are places where an
array set to zero is then assumed to be an array of NULL pointers,
and numerous other implicit uses of the fact that NULL == 0 (usually).

>In fact, I much prefer (from a C style article posted a few years back):
>
>x()
>{
>	if (sptr= (struct xyzzy *)malloc(...), !sptr)
>		fatal("cannot malloc");
>}

This was from a *style* guide?  Yeah I suppose it works, though I am
too lazy to check if the comma operator has a guaranteed order of
evaluation.  I seldom use it.

Anyway, why the spurious comma operator?  Much simpler to write:

	if (! (sptr = (struct xyzzy *)malloc(...))
		fatal(...);

------

Disclaimer goes here.  This is my opinion and not Technical Support.
It's all my fault.



More information about the Comp.lang.c mailing list