8

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);
}
Sadique
  • 22,572
  • 7
  • 65
  • 91
Babanna Duggani
  • 737
  • 2
  • 12
  • 34

7 Answers7

7

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

yan
  • 20,644
  • 3
  • 38
  • 48
  • Seems to be a rather common mistake, at least GCC (probably other compilers, too) prints out a warning, if warnings are enabled: `warning: comparisons like 'X<=Y<=Z' do not have their mathematical meaning` – Saytonurn Mar 28 '11 at 17:06
2

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.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

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.

sth
  • 222,467
  • 53
  • 283
  • 367
Chaithra
  • 1,130
  • 3
  • 14
  • 22
0

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)
Community
  • 1
  • 1
Xiong Chiamiov
  • 13,076
  • 9
  • 63
  • 101
0

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);
}
Eugene Burtsev
  • 1,465
  • 4
  • 24
  • 45
0

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).

N 1.1
  • 12,418
  • 6
  • 43
  • 61
0
x<y // 1 as (10 < 20) will return 1
result of(x<y)<z // 1 as (1<5) will return 1 
Ashish Kasma
  • 3,594
  • 7
  • 26
  • 29