Operator Precedence - Expression Evaluation
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);
}
i=x<y<z;
, gets interpreted as i=(x<y)<z
, which in turn gets interpreted as i=1<z
, which evaluates to 1.
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.
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.
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);
}
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).
x<y // 1 as (10 < 20) will return 1
result of(x<y)<z // 1 as (1<5) will return 1
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)
精彩评论