相同“if"条件下的两个“=="等式运算符未按预期工作

我正在尝试建立三个相等变量的相等性,但以下代码没有打印它应该打印的明显正确答案.有人可以解释一下,编译器是如何在内部解析给定的 if(condition) 的吗?

I am trying to establish equality of three equal variables, but the following code is not printing the obvious correct answer which it should print. Can someone explain, how the compiler is parsing the given if(condition) internally?

#include<stdio.h>
int main()
{
        int i = 123, j = 123, k = 123;
        if ( i == j == k)
                printf("Equal
");
        else
                printf("NOT Equal
");
        return 0;
}

输出:

manav@workstation:~$ gcc -Wall -pedantic calc.c
calc.c: In function ‘main’:
calc.c:5: warning: suggest parentheses around comparison in operand of ‘==’
manav@workstation:~$ ./a.out
NOT Equal
manav@workstation:~$

根据下面给出的答案,以下语句是否可以检查以上相等性?

Going by the answers given below, is the following statement okay to check above equality?

if ( (i==j) == (j==k))

推荐答案

  if ( (i == j) == k )

  i == j -> true -> 1 
  1 != 123 

为了避免这种情况:

 if ( i == j && j == k ) {

不要这样做:

 if ( (i==j) == (j==k))

你会得到 i = 1, j = 2, k = 1 :

You'll get for i = 1, j = 2, k = 1 :

 if ( (false) == (false) )

...因此错误的答案;)

... hence the wrong answer ;)

相关文章