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?
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.
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 .
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.
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.
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.)
It's not possible, you have to split the check as you did in case 2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With