Interview Questions

I need to check whether one number lies between two others

C Interview Questions and Answers


(Continued from previous question...)

I need to check whether one number lies between two others

Q: I need to check whether one number lies between two others. Why doesn't
if(a < b < c)
work?

A: The relational operators, such as <, are all binary; they compare two operands and return a true or false (1 or 0) result. Therefore, the expression a < b < c compares a to b, and then checks whether the resulting 1 or 0 is less than c. (To see it more clearly, imagine that it had been written as (a < b) < c, because that's how the compiler interprets it.) To check whether one number lies between two others, use code like this:
if(a < b && b < c)

(Continued on next question...)

Other Interview Questions