Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
658 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 
"):
        printf("False 
");
}
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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...