为什么将三个变量与 == 一起比较会计算为 false?

Why comparing three variables together with == evaluates to false?

本文关键字:比较 一起 false 计算 变量 三个 为什么      更新时间:2023-10-16

以下程序的输出是"它们不相等",但我希望"它们是相等的",因为三个比较变量(xyz(是相等的。为什么?

#include <iostream>
int main()
{
int y, x, z;
y = 3;
x = 3;
z = 3;
if (x == y == z)
{
std::cout << "they are equaln";
}
else
{
std::cout << "they are not equaln";
}
}

这是因为计算表达式和类型的方式。

让我们评估最左边的==

x == y ...

此计算结果为 true。让我们重写表达式:

//  x == y
if (true   == z) {
// ...
}

true是一个布尔值。布尔值不能直接与int进行比较。必须从布尔值转换为整数,结果1(是的,true==1(。让我们将表达式重写为其等效值:

//  true
if (1    == z) {
//    ^--- that's false
}

z不等于1。这句话是假的!

相反,您应该将两个布尔表达式分开:

if (x == y && y == z) {
// ...
}

现在还有一些实用的 C++17 应用程序。无需 SFINAE。

//----------------------------------
// constexpr lambda requires C++17
auto eq3 = [] (auto v1, auto v2, auto v3) constexpr -> bool
{
return ( v1 == v2 ) && ( v2 == v3 );
};

用法很简单,但完全编译

constexpr auto same_ = eq3(42,42,42);
std::bool_constant< eq3(42,42,42) > twins_ ;

对于比较整个值序列,概念是相同的,即兴更复杂。

template<typename ... T>
constexpr bool all_equal ( const T & ... args_ )  
{
if ((sizeof...( args_) ) < 2) return true;
// for non recursive version
const auto il_ = { args_ ... };
// compare them all to the first
auto first_ = *(il_.begin()) ;
// assumption
bool rezult_{ true }; 
for ( auto && elem_ : il_) {
// yes I know, first cycle compares first_ to itself ...
rezult_ = rezult_ && ( first_ == elem_ );
// short circuit-ing
if (!rezult_) break;
}
return rezult_; 
};

"只是"一个函数,编译时,再次没有可变参数模板欺骗。

bool_constant< all_equal(42,42,42,42,42,42,42) > same_ ;
cout << endl << boolalpha <<  same_() ;
bool_constant< all_equal(42,43,44,45,46,47) > not_same_ ;
cout << endl << boolalpha <<  not_same_() ;

强制性魔杖盒在这里。

ps:有点可预测all_equal不会使用最新的CL(也称为MSVC或Visual Studio(进行编译。