+2

Can anyone explain what is this ?

Please tell about how the operators work. Cout<< ( ( 1 > 2 ) ? 3 : 4 ) ; ans: 4 int i=0 ; Cout <<( i=0 ? 1 : 2 ? 3 : 4 ) ; ans:3

3 Answers

New Answer

+9

The ternary operator works like a shorthand of `if` statement <expression> ? <true-block> : <false-block> Equal to: if(<expression>) <true-block> else <false-block> ● Now for first case: ((1 > 2) ? 3 : 4) - 1 is less than 2, so expression `1 > 2` is evaluated as false. ((false) ? 3 : 4) - 4 is returned here, because expression evaluates to false. ● For the second case: int i = 0; - Remember in C/C++ any non zero integral value is considered true. (i = 0 ? 1 : 2 ? 3 : 4) - Here zero is assigned to variable <i> then <i> is evaluated, which yields false because <i> is zero. ((false ? 1 : 2) ? 3 : 4) - `(false ? 1 : 2)` returns 2. Again non zero value is considered true, and zero is false. ((2) ? 3 : 4) - Since 2 is considered true (as it is non zero), here ternary operator returns 3. Hth, cmiiw

+6

You're very welcome buddy 👍

+3

Thanks Ipang , your answer is like a tutorial,it cleared all my doubts.