Path: csiph.com!news.mixmin.net!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail
From: Tim Rentsch
Newsgroups: comp.lang.c
Subject: Re: getFirstDayOfMonth()
Date: Thu, 14 Mar 2024 15:57:54 -0700
Organization: A noiseless patient Spider
Lines: 44
Message-ID: <86msr0pgjx.fsf@linuxsc.com>
References: <7VrEN.517245$xHn7.96511@fx14.iad> <87ttloqnnk.fsf@nosuchdomain.example.com> <20240305003723.000045a3@yahoo.com>
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Injection-Info: dont-email.me; posting-host="c73a7ccbfb7c95d529f92c065d1adb1d"; logging-data="1995588"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/frQnfyCMlAfcGS70/2MC7cQnaZPbEyN8="
User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux)
Cancel-Lock: sha1:a+pxtb3PyVnuHfDbDfi7aEX2CDI= sha1:wFz7A3+Pow/NaK6gr8wb8DuY/UM=
Xref: csiph.com comp.lang.c:383617
Michael S writes:
> On Mon, 4 Mar 2024 21:21:25 -0000 (UTC)
> Lew Pitcher wrote:
[...]
>> If you want to /guarantee/ that the return value of strcmp()
>> is -1, 0, or +1 (for "less than", "equal to", or "greater than")
>> you will have to process the return value with something like
>>
>> /*
>> ** Returns -1 if argument < 0, 0 if argument == 0, 1 if argument > 0
>> */
>> int iSignOf(int valu)
>> {
>> return ((valu > 0) - (valu < 0));
>> }
>
> Too tricky to my liking.
> I'd rather write straight-forward code and let compiler to figure
> out the best sequence.
>
> int iSignOf(int val)
> {
> if (val < 0)
> return -1;
> if (val > 0)
> return +1;
> return 0;
> }
I've seen the idiomatic form before, and my reaction to it is
more of it being overly cute than overly tricky. That said,
it is a bit on the tricky side; even so, I'm not sure the cure
suggested is much better than the disease. I would simply write
a single return statement:
return val < 0 ? -1 : val > 0 ? 1 : 0;
(possibly condensed to take advantage of the 0/1 result of the
"greater than" operator for non-negative operands).
I suppose some people prefer the multiple return form to the ?:
form, although I'm not sure why except perhaps as a carryover
from earlier experience.