Search code examples
c++syntaxevaluationcomparison-operators

Why does a combined upper and lower bound comparison always evaluate to true?


Why does the first always evaluate to true? I would expect these two statements to behave identically.

   for (int i =0;i<4;++i) (0 < i < 3) ? cout << "True " : cout << "False ";

True True True True

    for (int i =0;i<4;++i) (0 < i && i < 3) ? cout << "True " : cout << "False ";

False True True False


Solution

  • The condition 0 < i < 3 is really (0 < i) < 3.

    And it doesn't matter if 0 < i is true or not, as the result (0 for false and 1 for true) will always be less than 3.

    If you want to make sure i is within a range, you need multiple separate comparisons: 0 < i && i < 3, as you do in the second loop.