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>
)?
The return type of ternary expression is bounded to type (char *), yet the expression returns int, hence the program fails. Literally, the program tries to print string at 0th address at runtime.
Conditional AND The operator is applied between two Boolean expressions. It is denoted by the two AND operators (&&). It returns true if and only if both expressions are true, else returns false.
In a ternary operator, we cannot use the return statement.
The first is a comparison argument. The second is the result upon a true comparison. The third is the result upon a false comparison.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With