user14085433
user14085433

Reputation:

Why here error comes in ternary Operator?

The below statement gives error "unexpected type"

int i = 3;
System.out.println( (i==3) ? i+=3 : i-=3);

why this happens ?

Upvotes: 3

Views: 98

Answers (1)

Thomas
Thomas

Reputation: 182083

It's due to operator precedence: the += and -= assignment operators have lower precedence than the ? : ternary conditional expression operator.

There is only one way to interpret the i+=3 because it's followed by a :, namely, as the first branch of the ternary. But the -=3 is ambiguous and resolved according to precedence. Because the ternary has higher precedence, the expression is parsed like this:

((3==3) ? (i+=3) : i) -= 3

which is obviously nonsense, because you cannot assign to the result of an expression.

It works if you add extra parentheses to make the assignments take precedence:

(3==3) ? (i+=3) : (i-=3)

The parentheses around i+=3 are optional but recommended for readability (insofar as this thing is ever going to be readable).

Upvotes: 8

Related Questions