Two #39;==#39; equality operators in same #39;if#39; condition are not working as intended(相同“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"条件下的两个“=="等式运算符未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:相同“if"条件下的两个“=="等式运算符未按预期工作
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
