Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional operator mis-matching

When I execute in python following code

print(0<5<2)

It gives False as output but same thing in C++

std::cout<<(0<5<2);

returns True

Why this contradiction?

like image 992
Wrench Avatar asked Mar 24 '26 21:03

Wrench


2 Answers

In Python, 0 < 5 < 2 is equivalent to 0 < 5 and 5 < 2.
In C++, it is equivalent to static_cast<int>(0 < 5) < 2.

The Python shorthand is originally inspired by mathematics, but has been so generalized that you can write really strange stuff, like

>>> 1 < 5 in [2,3,4]
False
>>> 1 < 5 in [2,3,5]
True

and confuse all your friends.

like image 68
molbdnilo Avatar answered Mar 27 '26 09:03

molbdnilo


Because they are different language that has different syntax and work differently.

In the case of c++, the statement is evaluated from left to right.

0<5 == true

true < 2, this will trigger an implicit conversion from true to 1

1 < 2 == true, which is the end result

Python has different rules for how the language works. I don't know them, but clearly they lead to different result in this case.

like image 26
super Avatar answered Mar 27 '26 09:03

super



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!