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:
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?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)
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With