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?
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);
.
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.
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