Re: Chained comparisons [was: Array irregularites in C++]
In article <J9vL5t.12nM@beaver.cs.washington.edu>,
"Andrei Alexandrescu (See Website For Email)"
<SeeWebsiteForEmail@erdani.org> wrote:
That is, multiple ordering comparisons will be allowed and will be
chained as per math rules:
if (a == b == c) {...} // are a, b, and c all equal?
if (a != b != c != a) {...} // are a, b, and c distinct?
if (a <= b < c) {...} // is b in [a, c)?
...
Such tests are frequent in scientific code, and are consistent with
expressions you'd find in a math book.
"Consistent with" is stretching things a little bit. Math books are
usually asserting that these things are equal/not equal/etc., not
actually questioning ('if') whether or not they are.
A nice practical shortcut is that expressions in between two comparison
operators are evaluated at most once. I'm saying "at most" because the
comparison may be never executed, e.g.:
if (a != b != c != a) {...} // are a, b, and c distinct?
If a == b, then the rest of comparisons are never evaluated, nor is c.
The question is, what would be best to be consistent with? The language,
or the math?
Although it is a really neat feature to have*, fitting in with the
language is far more important. Otherwise, you start having to invent
even more special case syntax/semantics to handle things like:
fn(bool z)
{
if ((a == b) == z) //...
}
Ultimately, it just makes the language harder to program in.
*Icon has this feature, and it fits in that language in a general way,
because testing ('if') whether an expression succeeds or fails is
separated from the resultant value of that expression (in the case of
binary operators, a reference to whatever is on the right hand side).
--
Nevin ":-)" Liber <mailto:nevin@eviloverlord.com> 773 961-1620
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]