Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java prefix and unary operators together

I was working on Java prefix operators and came across this behavior

i = +--j //does not give an error
i = -++j //does not give an error

i = ---j //gives an error
i = +++j //gives an error

Why is this happening?

like image 372
Kiran Avatar asked Feb 11 '16 17:02

Kiran


2 Answers

Since both + and +++ (or - and --) are left-associative, +++j is evaluated as ++(+j). Since ++ can only be applied to an l-value (i.e., a variable) and +j is not an l-value (variable), you get a compilation error.

You could use parentheses to fix this, though: i = +(++j);.

like image 111
Mureinik Avatar answered Sep 18 '22 08:09

Mureinik


The compiler uses greedy left-to-right selection of tokens. So when it sees +--j, the longest sequence that is a valid token is +, since +- is not a valid token, so it takes + as the first token. Then it looks at the next largest thing that can be identified as a token, which is --j. So the result is + --j

For ---j it sees -- as the longest valid token, then -j as the next valid token, and tries to put those together as -- -j which, as @Mureinik pointed out, is not valid.

like image 40
FredK Avatar answered Sep 20 '22 08:09

FredK