+ 5
Why x < y < z is bad practice?
People discourage to make if statement like (x < y < z) because its not valid. After i try myself on sololearn, surprisingly it works but with warning. I wonder why it works on sololearn and why people discourage to use this kind of statement. Makes me wonder how x < y < z works?
3 Answers
+ 13
4 < 5 < 2 is true aka 1
What the computer sees:
(4 < 5) < 2
= (1) < 2
= 1 aka true
It's comparing the "boolean" with an integer.
(The boolean is actually an integer 0 or 1)
+ 6
Do not chain relational operators like that in languages that are not strongly typed and where the Boolean result of the first operation can be directly compared with a numerical operand of the second operator.
0
itâs better to separate. If you do it, you may get error. the best way is always to make the condition one by one:
â if( a < b < c){}
â
if( b>a && b<c){}