Chaining multiple greater than/less than operators
The first does one comparison, then compares the result of the first to the second value. In this case, the operators group left to right, so it's equivalent to (10<a) < 0
. The warning it's giving you is really because <
will always yield 0 or 1. The warning is telling you that the result of the first comparison can never be less than 0, so the second comparison will always yield false.
Even though the compiler won't complain about it, the second isn't really much improvement. How can a number be simultaneously less than 0, but greater than 10? Ideally, the compiler would give you a warning that the condition is always false. Presumably you want 0<a<10
and a>0 && a<10
.
You can get the effect of the second using only a single comparison: if ((unsigned)a < 10)
will be true only if the number is in the range 0..10. A range comparison can normally be reduced to a single comparison with code like:
if ((unsigned)(x-range_start)<(range_end-range_start))
// in range
else
// out of range.
At one time this was a staple of decent assembly language programming. I doubt many people do it any more though (I certainly don't as a rule).
No it is not possible.
You have to use the second way by splitting the two conditional checks.
It's not possible, you have to split the check as you did in case 2.
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.)