Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, why can't I write i++++ or (i++)++?

When I try to write a postfix/prefix in/decrement, followed by a post/prefix in/decrement, I get the following error: Invalid argument to operation ++/--.

But, according to JLS:

PostIncrementExpression:
        PostfixExpression ++

and

PostfixExpression:
        Primary
        ExpressionName
        PostIncrementExpression
        PostDecrementExpression

so writing:

PostfixExpression ++ ++

should be possible... Any thoughts?

like image 763
John Assymptoth Avatar asked Jan 10 '11 21:01

John Assymptoth


2 Answers

Note that the raw grammar lacks any semantics. It's just syntax, and not every syntactically valid program will generally be valid. For example, the requirement that variables have to be declared before usage is typically not covered by the grammar (you can, but it's cumbersome).

Postfix-increment yields an rvalue – and just as you cannot postfix-increment literals, you cannot postfix-increment the result of i++.

Quoting from the JLS (3rd ed., page 486):

The result of the postfix increment expression is not a variable, but a value.

like image 62
Joey Avatar answered Sep 22 '22 17:09

Joey


The error tells you the answer:

unexpected type
required: variable
found   : value
        (i++)++;

So, the i++ evaluates to a value while the operator requires a variable.

like image 36
JOTN Avatar answered Sep 19 '22 17:09

JOTN