Reputation: 147
Explain pleasy why second expression returns false
cout << (4==4) << endl; //1
cout << (4==4==4) << endl; // 0
Upvotes: 2
Views: 167
Reputation:
You can not apply binary compare operators to more than two operants, reasonably (unless you have an overwrite making it possible, somehow).
To compare an unknown number of arguments:
#include <iostream>
template <typename A, typename B>
bool equal(const A& a, const B& b) {
return a == b;
}
template <typename A, typename B, typename ... Other>
bool equal(const A& a, const B& b, const Other& ... other) {
return a == b && equal(b, other ...);
}
int main() {
std::cout << equal(1, 1, 1) << '\n';
std::cout << equal(1, 2, 3) << '\n';
}
C++ 11
Upvotes: 1
Reputation: 361252
(4==4==4)
is basically ((4==4)==4)
which is (true == 4)
which is (1==4)
1 which is false
2 which is getting printed as 0
.
Note that ==
has associativity left-to-right, but that doesn't matter (in this case) because even if it had associativity right-to-left, the result would have been the same.
1. Due to integral promotion.
2. Note that one might tempted to think 4
in (true==4)
could be treated as true
(after all 4
is non-zero, hence true
). This thinking might conclude (true==4)
is (true==true)
which is true
. But that is not how it works. It is the bool which gets promoted to int, instead of int to bool.
Upvotes: 13
Reputation: 8333
4==4
evaluates to true
, which for the purpose of comparing it with 4
is converted to 1
. 1 == 4
is false
, which is 0
.
Upvotes: 2