Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the return type of a ternary operator determined? [duplicate]

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>)?

like image 714
Meraj al Maksud Avatar asked Aug 07 '19 19:08

Meraj al Maksud


People also ask

What is the return type of ternary operator?

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.

What is the return type of conditional operators?

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.

Can return be used in ternary operator?

In a ternary operator, we cannot use the return statement.

What are the types of ternary operator?

The first is a comparison argument. The second is the result upon a true comparison. The third is the result upon a false comparison.


1 Answers

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.

like image 65
NathanOliver Avatar answered Oct 07 '22 18:10

NathanOliver