简体   繁体   中英

compilation error with ternary operator

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 !

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

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

And as false ? y+=1 : x 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: = += -= *= /= %= &= ^= |= <<= >>= >>>=

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM