Search code examples
c++if-statementshort-circuiting

Why is 'if(1 == 1 == 1 == 1 == 1);' TRUE but 'if(-1 == -1 == -1 == -1 == -1);' FALSE?


if (1 == 1 == 1 == 1 == 1)
    std::cout << "right";

The code above shows 'right'.

if (-1 == -1)
    std::cout << "right";

The code above also shows 'right'.

if (-1 == -1 == -1)
    std::cout << "right";

The code above shows nothing. (It's because the if statement isn't TRUE I guess?)

I would like to know why this weird thing happens.

Because -1 is equal to -1 and this statement is always TRUE no matter how many times I repeat (as far as I know).


Solution

  • The conditions are evaluated from left to right, hence the following conditional statement

    if (-1 == -1 == -1)
        std::cout << "right";
    

    is equivalent to

    if (true == -1)//since -1 === -1
        std::cout << "right";
    

    equivalent to

    if (1 == -1) // true is casted to 1
        std::cout << "right";
    

    equivalent to

    if (false)
        std::cout << "right";
    

    So it's normal the statement std::cout << "right"; doesn't execute and you get nothing.