For nested if, what will be the equivalent operation

42 views Asked by At

For the if...else statement below

if (a > b) {
    max = a;
}
else {
    max = b;
}

will result shortcut as below?

max = (a > b) ? a : b;

What about this if and nested if statement?

if (a > b) {
    max = a;
}
else {
    if (c > d)
        max = c;
    else
        max = d;
}
1

There are 1 answers

0
AustinWBryan On

Just do:

max = (a > b) ? a :
      (c > d) ? c : d;

And this can be formatted to be arbitrarily long, so the formatting is important because ternary operators can get real confusing real fast. Consider:

max = (a > b) ? a :
      (b > c) ? b :
      (c ? d) ? c :
      (d ? e) ? d : e;

Verses:

max = (a > b) ? a : (b > c) ? b : (c ? d) ? c : (d ? e) ? d : e;