Unexpected C code output

What will 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();
}

In fact i=20<30<10, therefore, the condition is false, and the value ishould be 0, and iequal to 1. Why?

+3
source share
9 answers

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

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


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

+7
source

Comparison operators do not work. Your program is equivalent to:

i = (x < y) < z;

which is equivalent to:

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

i == 1. , :

i = 1 < 10;

:

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

< . x<y<z (x<y)<z. 1, 1 10, 1.

+1

, . :

int i = (x<y)<z;

x<y. true, 20<30, true - 1 . 1<z .

+1

- .

20 < 30 = true 1 < 10 TRUE

SO FINALLY TRUE

+1

< -, 20 30 ( 1), 1 10.

0

"1" . (20<30) < 10, 1 < 10, 1.

The problem is that you are comparing a boolean value with an integer value, which in most cases does not make sense.

0
source

The operator < binds from left to right.

So, x < y < zcoincides with( x < y ) < z

Your expression evaluates to:

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

<shines through from left to right, so a value of 20 <30 is true or a unit that is less than 10.

0
source

All Articles