0

Multiple Ternary Operator Usage Question

Had an interesting encounter with a question with more than one ternary operator: a=0; cout << (a = 0 ? 1 : 2 ? 3 : 4); return 0; // outputs 3 a = 0 evaluates true so we get 1. After this, how do we get 3? How is "1 : 2" a mathematical expression that can be evaluated by the "?" operator? Are we treating the 1 as a boolean? But then 2 wouldn't even be evaluated... What other concept is at play here?

25th Jul 2020, 4:24 AM
Solus
Solus - avatar
7 Answers
+ 3
Correct, all non zero integers evaluate to true. So in first ternary take 2 (the false way), in second ternary take 3 (the true way)
25th Jul 2020, 4:58 AM
Bilbo Baggins
Bilbo Baggins - avatar
+ 3
Bilbo Baggins What's the value of "a" after ternary conditinal and why?
25th Jul 2020, 5:33 AM
Kevin ★
+ 2
Wait! a=0 evaluates 0 (the value of a) because you are assigning (=), not comparing (==)
25th Jul 2020, 4:41 AM
Bilbo Baggins
Bilbo Baggins - avatar
+ 2
So if we assigned value 0 to a, the "a = 0" is evaluate to false? But how do we get to the output of 3? Do we treat this situation like how we would for the condition of an "if" statement? That is, all integer (negative and positive), except zero, evaluates to true?
25th Jul 2020, 4:53 AM
Solus
Solus - avatar
+ 2
thanks a lot
25th Jul 2020, 5:01 AM
Solus
Solus - avatar
+ 2
r̶e̶m̶ Kevin ★ cout << (a = 0 ? 1 : 2 ? 3 : 4); After the the a=0 step, we choose the one on the right ( 2 instead of 1), which is true by nature because all non-zero integers are true. Then we choose the one on the left (3) after that. For exercise: try figuring out why the expression (0 ? 100 : 0 ? 0 : 400 ? 0 : 500 ? 0 : 700) would evaluate to 700
25th Jul 2020, 5:38 AM
Solus
Solus - avatar
+ 2
Kevin ★ thanks for asking that 😊 The false way in first ternary operation is not taken because a=0 is false as I said before: assignment is less prioritary than ternary operator! The false way in first ternary operation is taken just because 0 is false. The result of the two ternary operations is finally assigned to 'a', which will take 3 as new value.
25th Jul 2020, 5:59 AM
Bilbo Baggins
Bilbo Baggins - avatar