0

what is equivalent statement for

int a=5>4?9<6?40:30:20

8th Aug 2017, 8:43 AM
suraj chauhan
suraj chauhan - avatar
3 Respuestas
+ 6
int a= (5 > 4 ? (9 < 6 ? 40 : 30 ) : 20); // a = 30 is equivalent to if (5 > 4){ if (9 < 6) cout << 40; else cout << 30; } else cout << 20; Usually people avoid using ternary operator
8th Aug 2017, 9:02 AM
Babak
Babak - avatar
+ 5
@Babak wrote: << usually people avoid using ternary operator >> I love ternary operator because it's a cool shorthand, since they are still easily readable... However, using nested ternaries is not good advised as readabily quickly disappear, so you need at least use parenthesis (rounded brackets) to make it more explicit, but doing: a = (b<42) ? 'not enough' : 'too much'; ... is clearly more simple than: if (b<42) { a = 'not enough'; } else { a = 'too much'; } So, I will rather write your example as: a = (5>4) ? ( (9<6) ? 40 : 30 ) : 20; (spacing is also important for readability ;P)
8th Aug 2017, 6:35 PM
visph
visph - avatar
+ 5
@visph Great explanation.
8th Aug 2017, 6:46 PM
Babak
Babak - avatar