Why is the following syntax correct:
x = y+++y;
Where it means
y++ + yory + ++ywhich meansy * 2 + 1(not sure about this, though: very ambiguous)
But this syntax is incorrect:
x = y+++++y;
Which should mean
y++ + ++y, which meansy * 2 + 2
Is there a reason for the incorrectness of this syntax? (Edit: thank you for explaining why it is invalid syntax, but that is not my intention with this question.)
(Edit: ofcourse I’m not using this in real code, purely in interest of parsers/lexers; but I wonder why the parser doesn’t like this; the last example even looks less ambiguous than the first one.)
(Edit:
int i = 0;
int j = (i = 3)+++i;
Is invalid too, though it seems very unambiguous to me, (i = 3) is a value, thus (value + value) and then the ++i value token.)
The parsing is greedy, that is , it looks for the longest matching token first. This simplify the implementations a lot (presumably). Also the Java language spec(3.2) says
So, for
y+++++y;the parser/tokenizer will break it down something like this:y++(as there is no+++operator,++is the longest that match the syntax of java)++(as there is no+++operator,++is the longest that match the syntax of java)+(This was the first thing that matches the syntax now)yEffectively it is parsed as
(y++) (++) (+y)the
++operator is defined for a variable, however the first expression (y++) returns a value. You can’t apply the next operator (++) to a value.This means that
x = y+++y;would be parsed asy++ + y, which is nothing wrong with.