C中的复合条件:if (0.0 <a <1.0) [英] Compound condition in C: if (0.0 < a < 1.0)
问题描述
我最近注意到以下表达式在我的编译器 (Clang) 中编译:
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?
推荐答案
由于 <
运算符的从左到右结合性,表达式条件 (0.0 表示
((0.0 ==
1 <1.0
或 0 <1.0
取决于 a
的值.
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
.
所以不,它与 if (0.0 < a && a < 1.0)
(也许你可能会从 Python 同情规则中混淆)但在 C 中它会被渗透为我在上面解释过.
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.
您可以在示例中观察到的差异 --- 0.0 <<1.0
== true
当 a
== 0.0
, where as (0.0 < a && a< 1.0)
== false,对于a
== 0.0
,下面是我的代码(阅读评论):
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;
}
输出:
True
False
检查它的工作@Ideone
这篇关于C中的复合条件:if (0.0 <a <1.0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!