Ternary operator

Is there any logical reason that will explain why in a triple optor, both branches must have the same base type or be convertible to one? What is the problem of the lack of this rule? Why can't I do this (this is not a good example, but it clarifies what I mean):

int var = 0;

void left();
int right();

var ? left() : right();
+3
source share
4 answers

Expressions must be of a type known at compile time. You cannot have expressions like "X or Y"; it must be one or the other.

Consider this case:

void f(int x) {...}
void f(const char* str) {...}

f(condition ? 5 : "Hello");

? , , , , . , , , .

, ( ).

+13

. , .

+6

, .

, .

+1
source

I think because the ternary operator must have a specific return value. It is difficult to do if the types of both branches are different or invalid.

0
source

Source: https://habr.com/ru/post/1785480/


All Articles