Search code examples
c++operator-precedenceconditional-operatorternary

Using ternary operator inside a condtional gives unexpected output


I'm trying to understand what the ternary operating is doing to give me this output. I would expect that the conditional would short circuit as soon as true == false evaluated to false but the result of return_value is true in this code.

#include <iostream>

int main()
{
    bool return_value = true == false &&
                        true == false &&
                        false ? (true == false) : true; // add parens to see expected output (false ? (true == false) : true);

    std::cout << std::boolalpha << return_value << std::endl;

    // expected output: false                                                                                                  
    // actual output  : true
}                                                                                       }

If I place parenthesis around the last condition (false ? (true == false) : true) then I get the output that I expect.

Is there an order of operations that I am misinterpreting?


Solution

  • It appears that the implicit order of operations is

    bool return_value = (true == false && true == false && false)
                      ? (true == false)
                      : true;
    

    Rather than

    bool return_value = true == false &&
                        true == false &&
                        (false ? (true == false) : true);