Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator precedence issue leads to "error: unexpected type"

Tags:

java

Since there have been so many operator precedence questions recently, I started playing with some code and came up with this:

int x = someNumber;
int y = --x++;

This gives:

Error: unexpected type

required: variable
found: value

I tried this because I was interested to learn how java would deal with the fact that postfix has a higher operator precedence than prefix. This seems like the above statement would lead to a contradiction, which I guess is handled by this error.

My question is two-fold:

  1. Why this error? What does it mean, exactly?
  2. Why does postfix have a higher precedence than prefix? I'm sure there's a good reason for it, but I haven't been able to come up with one. Perhaps it would fix this undefined behavior, but it would somehow give rise to more problems?
like image 486
Steve P. Avatar asked Jul 24 '13 15:07

Steve P.


2 Answers

The cause of the error is that x++ produces a value, and you can't apply a decrement operator to a value, only to a variable. For example if x=41, x++ evaluates to 41, not to the variable x, and --(41) is meaningless.

As to why postfix has higher precedence than prefix, my guess is that it is to avoid ambiguity with other operators while parsing. For example, the compiler can report a syntax error for x--x instead of parsing it as x-(-x).

like image 104
Joni Avatar answered Nov 09 '22 06:11

Joni


try

int y = 2++;

you will get the same error. Post/pre operator are applied on variable not on some number.Thats why you get error

 Error: unexpected type

Because it expects a variable not some number. Assume your number is 3

 int x = 3;
 int y = --x++;

int y become 2++ after applying -- operator on java (as java operator works 
from left   to  right)

I don't know what exactly you are trying to ask in second question. But take scenario

  int y = -x---x;

here also it will be operated from left to right which comes to

 (-x--)-(x) so answer will be -3 so dont get confused by postfix and prefix
like image 38
M Sach Avatar answered Nov 09 '22 06:11

M Sach