[comp.lang.c] Assignment in test: OK?read/new/followup

browns@iccgcc.decnet.ab.com (Stan Brown, Oak Road Systems) (09/12/90)

In article <18326@ultima.socs.uts.edu.au>, jeremy@sinope.socs.uts.edu.au (Jeremy Fitzhardinge) writes:
> How many would prefer
> 	if (thing != NULL)
> 	{
> 		fp = fopen(thing, "r");
> 		if (fp == NULL)
> 			barf();
> 	}
> to
> 	if (thing && (fp = fopen(thing, "r"))
> 		barf();
> ?

I would, for one.  The first one at least does the right thing.  But, depending
on context, I might prefer
        if (thing && !(fp = fopen(thing,"r"))
            barf( );
to both of them.

I'm not flaming you--my point is that when we write nice compact sexy
code that eliminates unnecessary lines, we unfortunately increase its
susceptibility to errors.  That little ! is awfully easy to leave out,
or to overlook if it's there.

Let's look at another alternative:
        if (thing && (NULL==(fp=fopen(thing,"r"))
            barf( );
Hmm, maybe.  Personally I think it's ugly, but the first one strikes me
as ugly also.  What's a programmer to do?
-- 

Stan Brown, Oak Road Systems, Cleveland, Ohio, U.S.A.         (216) 371-0043
The opinions expressed are mine. Mine alone!  Nobody else is responsible for
them or even endorses them--except my cat Dexter, and he signed the power of
attorney only under my threat to cut off his Cat Chow!