C程序中的意外输出

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.


请注意,关系运算符返回01取决于操作数之间的关系是否为falsetrue.

  • 我只想发布同样的事情.我打字太慢了 (2认同)
  • 答案可以通过以下方式得到改进:提到运算符关联性从">"向右.还要提及/链接运算符优先级/关联表,以便OP可以学习如何为其他运算符查找相同的信息. (2认同)