0
what is equivalent statement for
int a=5>4?9<6?40:30:20
3 odpowiedzi
+ 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
+ 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)
+ 5
@visph Great explanation.