Pre*_*ta 2 c relational-operators
我运行以下C程序
#include <stdio.h>
int main() {
int x = 5, y = 6, z = 3, i;
i = y > x > z;
printf("%d\n", i);
}
Run Code Online (Sandbox Code Playgroud)
并获得输出0.再次,当我跑
#include <stdio.h>
int main() {
int x = 5, y = 6, z = 3, i;
i = y > x && x > z;
printf("%d\n", i);
}
Run Code Online (Sandbox Code Playgroud)
我输出为1.任何人都可以解释这背后的逻辑吗?
hac*_*cks 10
关系运算符从左到右关联.因此i = y > x > z;将被解析为
i = ( (y > x) > z ) => ( (6 > 5) > 3 ) => ( 1 > 3 ) => 0
Run Code Online (Sandbox Code Playgroud)
并且i = y > x && x > z;会被解析为
i = (y > x) && (x > z) => (6 > 5) && (5 > 3) => 1 && 1 => 1
Run Code Online (Sandbox Code Playgroud)
也就是说,在C y > x > z中不检查是否x大于z和小于y.但是y > x && x > z.
请注意,关系运算符返回0或1取决于操作数之间的关系是否为false或true.