Reputation: 3381
From the perspective of Compiler Theory, why would the javac compiler not accept a statement of the form x = x+++++y
but accept x = x+++ ++y
?
Upvotes: 8
Views: 272
Reputation: 9538
Because ++
is a valid token for the java lexer, the statement x+++ ++y
will be parsed into tokens as :
(x)(++)(+)( )(++)(y)
Whereas x+++++y
will be tokenized into the invalid:
(x)(++)(++)(+)(y)
The above is invalid java because the ++
operator can only be applied to things that are numeric variables, which the result of (x++)
is not. This type of tokenizing is a great example of the concept known as maximal munch.
From the JLS section 3.2
The longest possible translation is used at each step, even if the result does not ultimately make a correct program while another lexical translation would.
Thus, the input characters a--b are tokenized (§3.5) as a, --, b, which is not part of any grammatically correct program, even though the tokenization a, -, -, b could be part of a grammatically correct program.
Upvotes: 9