2008-01-09

Chained comparisons

Have you ever wondered about writing

if( 0 <= x < max ) { ... }
in your program? Did it work? Like you intended?

The (by me) expected semantic for this expression is the same like the mathematical, or if you want to talk in C:
if( (0 <= x) && (x < max) ) { ... }
However in C, the <= operator is left-associative meaning, 0 <= is evaluated first and the integer 1 is the result if the test is true and the second test against max is made to this 1, thus the result is most likely a bug. C++ upholds this C legacy.

Java doesn't make it work, but at least detects it as an error through the dedication that comparisons in general result in an result of type boolean, thus you get this:
operator < cannot be applied to boolean,int
compiler error.

Python (tested) and Ruby (read) implement the "right" behavior, Perl 6 is about to implement it. Concerning D, I came across this discussion.

No comments: