To summarize it quickly, why isn't 2 < x < 9
equal to 2 < x && x < 9
?
This is the test code I've written:
#include <iostream> int main() { int nums[] = { 5 , 1, 10}; // We are gonna check if the number is in the range 2 - 9 for (auto e : nums) { if (2 < e < 9) std::cout << "2 < " << e << " < 9" << std::endl; if(2 < e && e < 9) std::cout << "2 < " << e << " and " << e << " < 9" << std::endl; } std::cin.get(); }
Here is the output I'm getting:
2 < 5 < 9 2 < 5 and 5 < 9 2 < 1 < 9 2 < 10 < 9
It looks like only 2 < e && e < 9
works correctly.
Equal to ( === ) — returns true if the value on the left is equal to the value on the right, otherwise it returns false .
Comparison operators are binary operators that test a condition and return 1 if that condition is logically true and 0 if that condition is false.
The three-way comparison operator <=> is often just called spaceship operator. The spaceship operator determines for two values A and B whether A < B, A = B, or A > B. You can define the spaceship operator or the compiler can auto-generate it for you. To appreciate the advantages of the three-way comparison operator, let me start classical.
The spaceship operator or the compiler can auto-generate it for us. Also, a three-way comparison is a function that will give the entire relationship in one query. Traditionally, strcmp () is such a function. Given two strings it will return an integer where, > 0 if the first string is greater.
The spaceship operator determines for two objects A and B whether A < B, A = B, or A > B. The spaceship operator or the compiler can auto-generate it for us. Also, a three-way comparison is a function that will give the entire relationship in one query. Traditionally, strcmp () is such a function. Given two strings it will return an integer where,
Also, a three-way comparison is a function that will give the entire relationship in one query. Traditionally, strcmp () is such a function. Given two strings it will return an integer where, > 0 if the first string is greater. It can give one of the three results, hence it’s a three-way comparison.
The expression
2 < x < 9
is grouped as
(2 < x) < 9
And since 2 < x
is either false
(0) or true
(1), and both are less than 9, it's always true
.
So unless you use overloaded operators for a non-built-in type x
(then a 3-way comparison would be possible if 2 < x
were to return an instance of a proxy object on which <
is defined), if you want to test if x
is in the interval (2, 9) you need to write it the way you have.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With