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"条件下的两个“=="等式运算符未按预期工作


基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何通过C程序打开命令提示符Cmd 2022-12-09