Search code examples
pythonc++logiccomparison-operators

Two comparison operators in c++ like python


Does the comparison 5 > x > 1 work in C++, like it does in python. It doesn't show any compiling errors but also doesn't seem to work.


Solution

  • In C++, 5 > x > 1 is grouped as (5 > x) > 1.

    (5 > x) is either false or true, and this is therefore never greater than 1, since false and true convert to 0 and 1 respectively. Hence

    5 > x > 1
    

    is false in C++, for any value of x. So in C++ you need to write the expression you really want with the longer form

    x > 1 && x < 5