Re: Memo on coding practices: strcmp() does not yield bool

From: Ed Loehr <eloehr(at)austin(dot)rr(dot)com>
To: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Cc: pgsql-hackers(at)postgresql(dot)org
Subject: Re: Memo on coding practices: strcmp() does not yield bool
Date: 2000-07-06 23:37:37
Message-ID: 39651841.8B7CD098@austin.rr.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: 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

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Jan Wieck 2000-07-07 00:05:07 Re: update on TOAST status'
Previous Message Tom Lane 2000-07-06 23:03:57 Memo on coding practices: strcmp() does not yield bool