+ 9

[ Solved ] Why comparison 5 <= x <= 10 wont work in below code

While x >= 5 && x <= 10 works fine. https://code.sololearn.com/cJzkCi5S0Aux/?ref=app

16th Jan 2021, 10:30 AM
Mr. Rahul
Mr. Rahul - avatar
9 odpowiedzi
+ 3
Comparison operators like < , >, == will compare the two elements and return either true (1) or false (0). In your case first 5<=x will be evaluated first and return 0 or 1 and both (0&1) less than 10. so this will create infinite loop and never comes out from while and causes runtime error. So to combine two or more comparison operation always use && , || to combine them.
18th Jan 2021, 9:52 AM
mahesh hegde
mahesh hegde - avatar
+ 4
Mr. Rahul No, C++ does not support that feature.
16th Jan 2021, 10:41 AM
luʁi
+ 4
Because in c++ you must write && for and
16th Jan 2021, 10:43 AM
Սոֆի
+ 3
Mr. Rahul I don't know much about cpp, but still let me try and answer your question. Suppose you have a statement- x = y = 5; Here first y is assigned 5 and then x is assigned the value of y i.e. 5. So we can say that the expression y = 5, it self returns a value of 5 which we then store in x. The takeaway here is that a relational expression and an assignment always returns a value. So 5 <= x <= 10 is confusing because if the expression x <= 10 returns true, 5 <= true doesn't make any sense. I hope it helped. If anywhere I was wrong, kindly correct me.
16th Jan 2021, 10:57 AM
Soumik
Soumik - avatar
+ 3
Mr. Rahul In java, booleans are not converted to 0s and 1s. So if you compare numbers with booleans, you get an error. Whereas, in cpp, the boolean is converted to numbers that's why your program is still working and that's the same reason why the compiler gives a warning.
16th Jan 2021, 11:05 AM
Soumik
Soumik - avatar
+ 2
Because the comparison x <= 5 will return a bool, which is then implicitely converted to an integer, i.e. 0 or 1, and either value is always smaller than 10. That is why you need the logical operators to chain multiple conditions together, e.g. &&.
16th Jan 2021, 10:36 AM
Shadow
Shadow - avatar
+ 2
Shadow sir Can i not compare it directly like 5 <= x <= 10 While using && operator like x >= 5 && x <= 10
16th Jan 2021, 10:39 AM
Mr. Rahul
Mr. Rahul - avatar
+ 2
Thx Devansh Singh Bisht But i know this way or more already🤗
16th Jan 2021, 10:58 AM
Mr. Rahul
Mr. Rahul - avatar
+ 2
♨ Soumik 🎶 I was simply taking x as integer And compare it ;if that integer is greater or equal to 5 and less or equal to 10 then return a string as output. But the comparison wont working in a single line as 5<= x <= 10 While i have to separate it with && operator for execution😑
16th Jan 2021, 11:02 AM
Mr. Rahul
Mr. Rahul - avatar