Why does the expression:
-5 < -3 < -1
evaluate to 0 in MATLAB? The separate statements each evaluate to true, so I'm confused as to why it's evaluating to false.
Many thanks.
Because it really looks like this:
(-5 < -3) < -1
-5 < -3 is true, which is also 1.
1 < -1 is false, which is also 0.
Final answer: 0.
MATLAB operates left to right for the less than operator.
So you are evaluating
-5 < -3 < -1
TRUE < -1
FALSE
-5 < -3 < -1
statement because they care that booleans can't be compared with integers, but in less strict languages a boolean TRUE is exactly the same as an integer 1 (any non-zero value evaluates to true, but true is explicitly stored as 1). So I immediately understood what was going on. The parens are also something that's always there. Even 5 + 3 + 2
is really (5 + 3) + 2
but we don't write them down.
Dec 15, 2015 at 19:11
-5 < -3 < -1
is equivalent to doing -5 < -3 && -3 < -1
, which will evaluate to True
link - start at Comparisons can be chained arbitrarily.... We can't assume that this assumed behaviour is the same amongst all programming languages. That's why I prefer this answer as it linked to official documentation. FWIW, I did upvote your answer as it got to the point quickly but you can't assume from logic that your answer holds True for all programming languages.
-5 < -3
or -3 < -1
is evaluated first... Tough luck or something I guess. I would say it is good practice to have parathesis where they belong in case of operators with the same priority.
(-5 < -3) && (-3 < -1)