Dheeraj Verma
Dheeraj Verma

Reputation: 79

Boolean output with comparison operator

Why the output of the following C code is 1 (True)?

#include<stdio.h>
main()
{
    int a, b = 1, c = 3, d = 2;
    a = b < c < d;
    printf("%d",a);
}

While the same expression gives "False" in python.

Upvotes: 1

Views: 253

Answers (3)

Lucas Sirignano
Lucas Sirignano

Reputation: 27

a = ( b < c && c < d)

should return the value that you want.

Upvotes: -2

Gopi
Gopi

Reputation: 19864

Check the order of evaluation from left to right.

b<c is true so it returns 1.

Then

1<d Yes so you get 1

So

a=1

Make sure since you are using relational operators the value returned will be true or false. i.e 0 or 1

Upvotes: 3

Vlad from Moscow
Vlad from Moscow

Reputation: 310990

Statement

a=b<c<d;

is equivalent to

a = ( b < c ) < d;

It is not the same as

a = ( b < c ) && ( c < d );

According to the C Standard (6.5.8 Relational operators)

6 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.107) The result has type int.

So in this statement

a = ( b < c ) < d;

as b is less than c then the result of subexpression ( b < c ) will be equal to 1 according to the quote of the Standard. And 1 is less than d that is equal to 2. So the overall result is 1.

Upvotes: 2

Related Questions