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 condit开发者_开发问答ion is false and the value of i
should be 0 but i
equals 1. Why?
This int i=x<y<z;
doesn't work the way you intended.
The effect is int i=(x<y)<z;
, where x<y
is 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.
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);
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.
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.
Its precedence is from left to right. Thats is why it is like
20<30 = true 1<10 TRUE
SO FINALLY TRUE
Actually <
is left-associative, so first, 20<30 is evaluated (giving 1 usually), then 1 is less than 10.
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.
< is evaulated from left to right, so 20<30 is true, or one, which is less than 10.
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
精彩评论