-1

I found this question in many interviews and my teacher asked me the same the main doubt was that if I include <stdbool.h> in C99 standard will that evaluate this as (true)<c or (false)>c. Need a more clear answer than the linked post --> Usage of greater than, less than operators .

How a<b<c or a>b>c are evaluated in C
for example in the following code.

# include<stdbool.h> 
int main(void){
    int a = 1,b=2,c=3;
    if(a<b<c)
        printf("a great b great c");
    }

thank you in advance.

Optimus Prime
  • 69
  • 2
  • 13
  • I assume that you want to evaluate in its mathematical sence: b is between a and c. This does not work, because independently of the execution order, the result of the first subexpression is 0 or 1, depending on what is correct. The second comparision is than compared against this result. – Amin Negm-Awad Dec 20 '17 at 18:52
  • 1
    Possible duplicate of [Usage of greater than, less than operators](https://stackoverflow.com/questions/6961643/usage-of-greater-than-less-than-operators) – Bo Persson Dec 20 '17 at 20:05
  • @BoPersson can you answer the same as i have mentioned what I'm actually seeking no one mentioned the same in the answer. – Optimus Prime Dec 22 '17 at 04:30
  • 1
    `` just contains things like `#define true 1` and doesn't affect the result at all. – Bo Persson Dec 22 '17 at 05:21

2 Answers2

7

From standard itself (Relational operators footnotes)

The expression a<b<c is not interpreted as in ordinary mathematics. As the syntax indicates, it means (a<b)<c; in other words, if a is less than b, compare 1 to c; otherwise, compare 0 to c.

user2736738
  • 30,591
  • 5
  • 42
  • 56
0

Operator associativity dictates that a<b<c is equivalent to (a<b)<c (as opposed to a<(b<c)).

If a is less than b, a<b evaluates to 1. Otherwise, 0.

If the value returned by a<b (1 or 0) is less than c, the whole evaluates to 1. Otherwise, 0.


From the spec

Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false.) The result has type int.

ikegami
  • 367,544
  • 15
  • 269
  • 518