Re: Position of test values in conditional expressions

From: Gerry Quinn (gerryq_at_DELETETHISindigo.ie)
Date: 06/24/04


Date: Thu, 24 Jun 2004 17:34:41 +0100

In article <40DADBC3.F9457AF1@yahoo.com>, cbfalconer@yahoo.com says...
> Gerry Quinn wrote:
> >
> ... snip ...
> >
> > "if ( x = y )" is perfectly legitimate syntax, but it's a pattern
> > that most programmers rarely if ever use.
> >
> > Some people probably love it for its compactness, and they should
> > turn the warning off. I would consider it to fall into the
> > category of obfuscated code, and its use would require very
> > special circumstances (can't think of any offhand).
>
> I gave at least one in <40D8ED16.BBA5C7F8@yahoo.com> a couple of
> days ago.

I would consider your example to be obfuscated code.

Your example:
<QUOTE>
void foo(int count, char *fn)
{
    FILE *fp = NULL;
    bar *buf;

    if (!(buf = malloc(count * sizeof *buf))) err("No mem");
    else if (!(fp = fopen(fn, "r")) err("can't open");
    else {
       /* do my thing with fp and buf */
    }
    if (fp) fclose(fp);
    free(buf);
}
<END-QUOTE>

I don't use C anyway but if I were writing that it would look something
like the following:

void foo(int count, char* fn )
{
        FILE* fp = NULL;
        bar* buf;
        
        buf = malloc( count * sizeof( *buf ) );
        if ( buf == 0 )
        {
                err( "No mem" );
        }
        else
        {
                fp = fopen( fn, "r" );
                if ( ! fp )
                {
                        err( "can't open" );
                }
                else
                {
                        /* do stuff */
                        fclose( fp );
                }
        }
        free( buf );
}

I might lose the if-elses by creating a do-loop or tracking successes
with a flag, but that's another issue.

Why do you think the above is a problem? Is it just that it's too long
for cut-and-paste? Of course one virtue of C++ is that you can usually
create a class to embody such things compactly.

- Gerry Quinn



Relevant Pages