c++operatorsinequalityrelational-operators

Why does the following inequality evaluate to true in C++?


The following piece of code seems so trivial. I don't understand why its not working.

float bound_min   = +314.53f;
float bound_max   = +413.09f;
float my_variable = -417.68f;

if (bound_min <= my_variable <= bound_max)
{
    printf("Why on earth is this returning True?");
}   

Can a C++ wizard of stackoverflow please come and rescue me?


Solution

  • The condition in the if statement

    if (bound_min <= my_variable <= bound_max)
    

    is equivalent to

    if ( ( bound_min <= my_variable ) <= bound_max)
    

    The first subexpression ( bound_min <= my_variable ) evaluates to boolean false.

    So as a result you have

    if ( false  <= bound_max)
    

    In this result expression the boolean false is converted to the integer 0 due to the integral promotions.

    if ( 0 <= bound_max)
    

    So the final value of the condition is true.

    From the C++ 17 Standard (8.9 Relational operators)

    1 The relational operators group left-to-right.

    [Example: a<b<c means (a<b)<c and not (a<b)&&(b<c) —end example] .