Question
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?
Answer
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.)