相同“if"条件下的两个“=="等式运算符未按预期工作 [英] Two '==' equality operators in same 'if' condition are not working as intended

查看:28
本文介绍了相同“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 ;)

这篇关于相同“if"条件下的两个“=="等式运算符未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆