Babanna Duggani
Babanna Duggani

Reputation: 727

Operator Precedence - Expression Evaluation

For the following code snippet I get the output as 1. I want to know how it came?

void main()
{
int x=10,y=20,z=5,i;
i=x<y<z;
printf("%d",i);
}

Upvotes: 8

Views: 2059

Answers (7)

Xiong Chiamiov
Xiong Chiamiov

Reputation: 13684

C++ doesn't support multi-part comparisons like that.

x < y < z

is interpreted as

(x < y) < z

or that is, determine if x < y, then see if that boolean is less than z.

There's some discussion on why that is over at the software engineering StackExchange.

When you find yourself trying to do this, instead you need to write it as two separate comparisons joined by a boolean:

(x < y) && (y < z)

Upvotes: 0

Chaithra
Chaithra

Reputation: 1140

It operates as follows: Since < is a logical expression, x<y i.e 10<20 is true i.e 1. So it becomes 1<z i.e 1<5 which is again true i.e. 1 which is assigned to i. So i is 1.

Upvotes: 1

Ashish Kasma
Ashish Kasma

Reputation: 3642

x<y // 1 as (10 < 20) will return 1
result of(x<y)<z // 1 as (1<5) will return 1 

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798456

10 is less than 20, resulting in 1, and 1 is less than 5, resulting in 1. C doesn't chain relational operators as some other languages do.

Upvotes: 2

N 1.1
N 1.1

Reputation: 12524

what output did you want?

In C,

i = 2 < 3; //i == 1.
i = 4 < 3; //i == 0.

If condition evaluates to false, value returned is 0, and 1 otherwise.
Also, x < y < z will be evaluated as ((x < y) < z).

Upvotes: 0

yan
yan

Reputation: 20982

i=x<y<z;, gets interpreted as i=(x<y)<z, which in turn gets interpreted as i=1<z, which evaluates to 1.

Upvotes: 7

Eugene Burtsev
Eugene Burtsev

Reputation: 1475

This is because your code evaluates as:

void main()
{
    int x=10,y=20,z=5,i;
    i=((x<y)<z); //(x<y) = true = 1, (1 < 5) = true
    printf("%d",i);
}

Upvotes: 0

Related Questions