Alex Rivera | Logout

What is the result type of '?:' (ternary/conditional operator)?

Asked 2011-12-16T13:57:39.373
217

Why does the first conditional operator result in a reference?

int x = 1;
int y = 2;
(x > y ? x : y) = 100;

However, the second does not.

int x = 1;
long y = 2;
(x > y ? x : y) = 100;

Actually, the second does not compile at all:

error: lvalue required as left operand of assignment
      |     (x > y ? x : y) = 100;
      |     ~~~~~~~^~~~~~~~
Edit
Report

2 Answers

61

The type of the ternary ?: expression is the common type of its second and third argument. If both types are the same, you get a reference back. If they are convertable to each other, one gets chosen and the other gets converted (promoted in this case). Since you can't return an lvalue reference to a temporary (the converted / promoted variable), its type is a value type.

answered 2011-12-16T13:59:32.290
19

It cannot return a lvalue since it will have to implicitly promote the type of x to match the type of y (since both sides of : are not of the same type), and with that it has to create a temporary.


What does the standard say? (n1905)

Expressions 5.17 Assignment and compound assignment operators

5.17/3

If the second and third operand have different types, and either has (possibly cv-qualified) class type, an attempt is made to convert each of those operands to the type of the other. The process for determining whether an operand expression E1 of type T1 can be converted to match an operand expression E2 of type T2 is defined as follows:

— If E2 is an lvalue: E1 can be converted to match E2 if E1 can be implicitly converted (clause 4) to the type “reference to T2”, subject to the constraint that in the conversion the reference must bind directly (8.5.3) to E1.

— If E2 is an rvalue, or if the conversion above cannot be done:

— if E1 and E2 have class type, and the underlying class types are the same or one is a base class of the other: E1 can be converted to match E2 if the class of T2 is the same type as, or a base class of, the class of T1, and the cv-qualification of T2 is the same cv-qualification as, or a greater cv-qualification than, the cv-qualification of T1. If the conversion is applied, E1 is changed to an rvalue of type T2 that still refers to the original source class object (or the appropriate subobject thereof). [Note: that is, no copy is made. — end note] by copy-initializing a temporary of type T2 from E1 and using that temporary as the converted operand.

Otherwise (i.e., if E1 or E2 has a non class type, or if they both have class types but the underlying classes are no

answered 2011-12-16T14:00:46.393

Your Answer