Operator Precedence - Expression Evaluation

感情迁移 提交于 2019-12-12 10:36:17

问题


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);
}

回答1:


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




回答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.




回答3:


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.




回答4:


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);
}



回答5:


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




回答6:


x<y // 1 as (10 < 20) will return 1
result of(x<y)<z // 1 as (1<5) will return 1 



回答7:


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)


来源:https://stackoverflow.com/questions/5459880/operator-precedence-expression-evaluation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!