问题
I have this question & in the answer it says that due to left to right associativity the result would be 1 that is true for this statement. This is the code.
#include<stdio.h>
int main ()
{
int i=0,x=10,y=10,z=5;
i=x<y<z;
printf("\n\n%d",i);
return 0;
}
But x is greater than z here so how is this happening ?
回答1:
The expression x
(x < y) < z
so it becomes
(10 < 10) < 5
which further is evaluated into
0 < 5
which is true.
I think you wanted something like this:
x < y && y < z
回答2:
Because of operator precedence and associativity
i = x < y < z;
is parsed as:
i = ((x < y) < z);
After substituting the variable values, this becomes:
i = ((10 < 10) < 5);
Since 10 < 10
is false, this becomes:
i = (0 < 5);
Since 0 < 5
is true, that becomes:
i = 1;
回答3:
x<y<z
is not a single valid expression. Instead it evaluates x<y
first (operator precedence is done left to right here) as true/false (false in this case as they're equal), converts it to an int value of 0
, and then compares this value with z
.
Use (x < y && y < z)
instead.
回答4:
It first evaluates x < y
which is false (0), then 0 < z
which is true (1).
回答5:
WHat C compiler does is, in x<y<z
;
starts from left, so as x is not less than y therefore it replaces that expression with '0'
so it becomes 0<z
and as that is true. it set the variable to 1.
来源:https://stackoverflow.com/questions/21202683/if-x-10-y-10-z-5-how-is-xyz-true