+ 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?

10th Dec 2020, 10:44 PM
ZΛRTHΛИ
ZΛRTHΛИ - avatar
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)
10th Dec 2020, 10:51 PM
Kevin ★
+ 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.
11th Dec 2020, 1:24 AM
Sonic
Sonic - avatar
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){}
12th Dec 2020, 10:27 AM
As Manjaka Josvah
As Manjaka Josvah - avatar