Re: Memo on coding practices: strcmp() does not yield bool - Mailing list pgsql-hackers

From Ed Loehr
Subject Re: Memo on coding practices: strcmp() does not yield bool
Date
Msg-id 39651841.8B7CD098@austin.rr.com
Whole thread Raw
In response to Memo on coding practices: strcmp() does not yield bool  (Tom Lane <tgl@sss.pgh.pa.us>)
Responses Re: Memo on coding practices: strcmp() does not yield bool  (Tom Lane <tgl@sss.pgh.pa.us>)
List pgsql-hackers
Tom Lane wrote:
> 
> I've occasionally griped that I do not like the coding practice of
> writing
>         
> to mean
>         if (strcmp(foo, bar) != 0)
> ...
> My past objection to this has been purely stylistic: it's too easy
> to read these constructs backwards, eg to think "!strcmp()" means
> "not equal".  However, I've now had my nose rubbed in the fact that
> this habit is actually dangerous.
> 
> Up till just now, ruleutils.c contained code like this:
> 
>         bool        tell_as = FALSE;
> 
>         /* Check if we must say AS ... */
>         if (!IsA(tle->expr, Var))
>             tell_as = strcmp(tle->resdom->resname, "?column?");
> 
>         /* more code... */
> 
>         if (tell_as)
>             /* do something */
> 
> This is subtly wrong, because it will work as intended on many
> platforms.  But on some platforms, strcmp is capable of yielding
> values that are not 0 but whose low 8 bits are all 0.  Stuff that
> into a char-sized "bool" variable, and all of a sudden it's zero,
> reversing the intended behavior of the test.

I see your examples demonstrate the danger of inappropriate or
inattentive type conversion (e.g., splicing an int into a char), but I'm
missing the danger you see, beyond a style offense, of "if (strcmp(foo,
bar))"?

Regards,
Ed Loehr


pgsql-hackers by date:

Previous
From: Tom Lane
Date:
Subject: Memo on coding practices: strcmp() does not yield bool
Next
From: JanWieck@t-online.de (Jan Wieck)
Date:
Subject: Re: TOAST on indices