Why in conditional operator(?:
), second and third operands must have the same type?
My code like this:
#include
They don't really have to be the same type. For example, an expression like: int a = argc > 1 ? 2 : 'a';
is entirely permissible, even though 2
is of type int
, and 'a'
is of type char
.
There does have to be an implicit conversion to the same type though. The reason is simple: the operator has to yield one value, and the compiler has to be able to figure out the type of that value. If there's no implicit conversion between the two types, there's no one type for the expression to produce.