[Solved] Parenthesis, Comma Operator and Ternary operator combination equivalent in java


This:

w = (m<3?y--,m+=13:m++,d+153*m/5+15*y+y/4+19*c+c/4+5);

Works out to be the same as this:

if (m<3) {
    y--;
    m+=13;
} else {
    m++;
}
w = (d + (153*m/5) +(15*y) + (y/4) + (19*c) + (c/4) + 5);

Now for the explanation. There is an instance of the ternary operator here. The second clause is an expression which allows for the comma operator, while the third clause is a conditional expression meaning it can’t include the comma operator (not without surrounding parenthesis, at least). This means that the first comma you see is part of the second clause while the second comma marks the end of the conditional.

So the expression with implicit parenthesis would look like this:

w = (((m<3)?(y--,m+=13):m++), (d + (153*m/5) +(15*y) + (y/4) + (19*c) + (c/4) + 5));

And the part that makes up the conditional is:

(m<3)?(y--,m+=13):m++

And because this is the left operand of the comma operator, the result of the expression isn’t used so it can be pulled out of the larger expression:

(m<3)?(y--,m+=13):m++
w = (d + (153*m/5) +(15*y) + (y/4) + (19*c) + (c/4) + 5);

And the conditional can then be further translated into an if/else block as above.

1

solved Parenthesis, Comma Operator and Ternary operator combination equivalent in java