compilation error with ternary operator

106 views Asked by At

I tried the following with ternary operator and I do not understand why it is not compiling. The issue seems so small but I do not understand and hence bothers me -

Line 1 --> int a = false ? y+=1 : (x*=10);

Line 2 --> int b = false ? y+=1 : x*=10;

Line 1 compiles however Line 2 does not. Why ?

How is the parenthesis making a difference in case of 3rd operand and not the second operand. I didn't have to use parenthesis with anything else in the 2nd / 3rd operands (Unary, string, basic arithmetic ...) Why just assignment operator and that too specifically 3rd operand ?

Thanks in advance !

1

There are 1 answers

0
T.J. Crowder On BEST ANSWER

Without the () around x*=10, the entire left-hand operand of the *= operator is false ? y+=1 : x, as though you had:

int b = (false ? y+=1 : x)*=10;

And as false ? y+=1 : x isn't a variable, it can't be the left-hand operand of *=.

The assignment operators (including compound assignment, *= and such) are very, very low in the precedence list, below the conditional operator (? :):

Operators Precedence

  • postfix: expr++ expr--
  • unary: ++expr --expr +expr -expr ~ !
  • multiplicative: * / %
  • additive: + -
  • shift: << >> >>>
  • relational: < > <= >= instanceof
  • equality: == !=
  • bitwise: AND &
  • bitwise: exclusive OR ^
  • bitwise: inclusive OR |
  • logical: AND &&
  • logical: OR ||
  • ternary: ? :
  • assignment: = += -= *= /= %= &= ^= |= <<= >>= >>>=