Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining multiple greater than/less than operators

Tags:

c

In an if statement I want to include a range, e.g.:

if(10 < a < 0)

but by doing so, I get a warning "Pointless comparison". However, this works fine without any warning:

if(a<10 && a>0)

Is the first case possible to implement in C?

like image 786
jscode Avatar asked Aug 05 '11 19:08

jscode


People also ask

Can you chain == in Python?

Chaining with the comparison operator == returns True only if all values are equal. If there is even one different value, False is returned. Be careful when using the comparison operator != that returns True when the values are not equivalent.

What are the 2 comparison operators?

Comparison OperatorsLess than ( < ) — returns true if the value on the left is less than the value on the right, otherwise it returns false . Greater than ( > ) — returns true if the value on the left is greater than the value on the right, otherwise it returns false .

Does Python allow chained comparison?

Python supports chaining of comparison operators, which means if we wanted to find out if b lies between a and c we can do a < b < c , making code super-intuitive. Python evaluates such expressions like how we do in mathematics.

How do you use multiple logical operators in Python?

There are three possible logical operators in Python: and – Returns True if both statements are true. or – Returns True if at least one of the statements is true. not – Reverses the Boolean value; returns False if the statement is true, and True if the statement is false.


2 Answers

Note that the original version if(10 < a < 0) is perfectly legal. It just doesn't do what you might (reasonably) think it does. You're fortunate that the compiler recognized it as a probable mistake and warned you about it.

The < operator associates left-to-right, just like the + operator. So just as a + b + c really means (a + b) + c, a < b < c really means (a < b) < c. The < operator yields an int value of 0 if the condition is false, 1 if it's true. So you're either testing whether 0 is less than c, or whether 1 is less than c.

In the unlikely case that that's really what you want to do, adding parentheses will probably silence the warning. It will also reassure anyone reading your code later that you know what you're doing, so they don't "fix" it. (Again, this applies only in the unlikely event that you really want (a < b) < c).)

The way to check whether a is less than b and b is less than c is:

a < b && b < c

(There are languages, including Python, where a < b < c means a<b && b<c, as it commonly does in mathematics. C just doesn't happen to be one of those languages.)

like image 61
Keith Thompson Avatar answered Oct 24 '22 05:10

Keith Thompson


It's not possible, you have to split the check as you did in case 2.

like image 29
user703016 Avatar answered Oct 24 '22 05:10

user703016