learnfromothers
learnfromothers

Reputation: 33

Unexpected output of C code

What would be the output of this program ?

#include<stdio.h>
#include<conio.h>
void main()
{
    clrscr();
    int x=20,y=30,z=10;
    int i=x<y<z;
    printf("%d",i);
    getch();
}

Actually i=20<30<10, so the condition is false and the value of i should be 0 but i equals 1. Why?

Upvotes: 3

Views: 184

Answers (9)

codaddict
codaddict

Reputation: 455440

The operator < associates from left to right.

So x < y < z is same as ( x < y ) < z

Your expression evaluates as:

  ( x < y ) < z
= ( 20 < 30 ) < 10
= ( 1 ) < 10
= 1 

Upvotes: 0

Bo Persson
Bo Persson

Reputation: 92381

This int i=x<y<z; doesn't work the way you intended.

The effect is int i=(x<y)<z;, where x<yis evaluated first, and the value true is then compared to z.


Pascal points out below that in C the result of the comparison is 1 instead of true. However, the C++ true is implicitly converted to 1 in the next comparison, so the result is the same.

Upvotes: 7

Stuti
Stuti

Reputation: 1638

Its precedence is from left to right. Thats is why it is like

20<30 = true 1<10 TRUE

SO FINALLY TRUE

Upvotes: 1

ralphtheninja
ralphtheninja

Reputation: 133238

< is evaulated from left to right, so 20<30 is true, or one, which is less than 10.

Upvotes: 0

Xeo
Xeo

Reputation: 131907

That's not how it works. It's better to see with parenthesis:

int i = (x<y)<z;

Now, first x<y is evaluated. It's true, 20<30, and true is 1 as an integer. 1<z is then true again.

Upvotes: 1

Joey
Joey

Reputation: 354864

The < operator has left-to-right associativity. Therefore x<y<z will do (x<y)<z. The result of the first parenthesis is 1, 1 is smaller than 10, so you'll get 1.

Upvotes: 1

Gunther Piez
Gunther Piez

Reputation: 30469

The output of "1" is correct. This is evaluated as (20<30) < 10, which is 1 < 10, which is 1.

The problem is that you are comparing a boolean value to an integer value which in most cases doesn't make sense.

Upvotes: 0

Diego Sevilla
Diego Sevilla

Reputation: 29019

Actually < is left-associative, so first, 20<30 is evaluated (giving 1 usually), then 1 is less than 10.

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272802

The comparison operators don't work like that. Your program is equivalent to:

i = (x < y) < z;

which is equivalent to:

i = (x < y);
i = i < z;

After the first operation, i == 1. So the second operation is equivalent to:

i = 1 < 10;

You need to rewrite your statement as:

i = (x < y) && (y < z);

Upvotes: 5

Related Questions