Compound condition in C: if (0.0 < a < 1.0)

百般思念 提交于 2019-11-26 18:34:51

问题


I recently noticed that the following expression compiles in my compiler (Clang):

float a;
if (0.0 < a < 1.0) { ... }

Does this do what I expect? I would expect that it evaluates identically to this condition:

if (0.0 < a && a < 1.0) { ... }

If it is so, since when and with which other compilers it is possible to write conditions in this short form?


回答1:


Because of left-to-right associativity of < operator the expression condition (0.0 < a < 1.0) means ((0.0 < a) < 1.0) == 1 < 1.0 or 0 < 1.0 depending on value of a.

So no, its not identical to if (0.0 < a && a < 1.0) (perhaps you might confusing from Python compassion rule) but in C it will be interpenetrated as I explained above.

A difference you can observe in an example --- 0.0 < a < 1.0 == true when a == 0.0, where as (0.0 < a && a < 1.0) == false, for a == 0.0, below is my code (read comments):

#include<stdio.h>
void print_(int c){
    c ? printf("True \n"):
        printf("False \n");
}
int main(void){
    float a = 0.0f;
    print_(0.0f < a < 1.0f); // 0.0 < 0.0 < 1.0f == 0 < 1.0f == True
    print_(0.0f < a && a < 1.0f); // 0.0f < 0.0f && ... ==  False && ... = False
    return 0;
}

output:

True 
False

Check its working @Ideone




回答2:


Does this do what I expect?

No, it does

(0.0 < a) < 1.0

and (0.0 < a) yields 0 or 1. So you end up having 0 < 1.0 or 1 < 1.0 evaluated.

Note that in some other languages it does what you expect.

For example in Python,

a < b < c

is called a chained comparison and it is equivalent to:

(a < b) and (b < c)



回答3:


Does this do what I expect?

No as it is very simple. < operator is having a left to right associativity it check as follows

(0.0 < a < 1.0 ) is simply

(0.0 < a) < 1.0

in second form

int main()
{
        float a = 8.4;
        if (0.0 < a && a < 9) //same as ( 0.0 < a) && (a < 9)
        printf("x");
}

o/p=x




回答4:


Maybe we can think in this way(just for fun):

if(0.0 <a < 1.0)

==>

if((0.0 <a)<1.0)

think :

if 0.0 < a == true, then (true <1.0) == false!

else if 0.0 < a == false ,then (false <1.0) == true!

So I can translate if(0.0 <a <1.0) to if(!(0.0<a))

Interesting , right?



来源:https://stackoverflow.com/questions/17878632/compound-condition-in-c-if-0-0-a-1-0

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