Search code examples
c++ternary-operatoroperator-precedence

How is the return type of a ternary operator determined?


I was solving a problem about movement of a bishop on a chessboard. At one point of my code, I had the following statement:

std::cout << (abs(c2-c1) == abs(r2-r1)) ? 1 : 2 << std::endl;

This generates the following error:

error: invalid operands of types 'int' and '<unresolved overloaded function type>' to binary 'operator<<'

However, I instantaneously fixed this error by including an additional variable in my code:

int steps = (abs(c2-c1) == abs(r2-r1)) ? 1 : 2;
std::cout << steps << std::endl;

How does the ternary operator work, and how is its return type determined (as the compiler called it <unresolved overloaded function type>)?


Solution

  • This has nothing to do with how the return type is deduced and everything to do with operator precedence. When you have

    std::cout << (abs(c2-c1) == abs(r2-r1)) ? 1 : 2 << std::endl;
    

    it isn't

    std::cout << ((abs(c2-c1) == abs(r2-r1)) ? 1 : 2) << std::endl;
    

    because ?: has lower precedence than <<. That means what you actually have is

    (std::cout << (abs(c2-c1) == abs(r2-r1))) ? 1 : (2 << std::endl);
    

    and this is why you get an error about an <unresolved overloaded function type>. Just use parentheses like

    std::cout << ((abs(c2-c1) == abs(r2-r1)) ? 1 : 2) << std::endl;
    

    and you'll be okay.