I was trying unary postfix and prefix operators in java
Here's the code
int a=10;
This line of code does not give compile time error
System.out.println(a+++ a +++a);
But this line does
System.out.println(a++ +++a);
whereas this line even doesn't
System.out.println(a+++ ++a);
I can't understand the pattern of how compiler interprets these queries.
System.out.println(a+++ a +++a);
is interpreted the same as
System.out.println(a++ + a++ + a);
It's compiled and executed as follows:
a
as the first operand; the first operand is now 10
a
(first a++
), its value is now 11a
as the second operand; the second operand is now 11 (as it was incremented in the previous step)a
(second a++
), its value is now 1210 + 11
to get 21 which is now the result of a++ + a++
, let's call this intermediate result i
, which will act as the first operand of the next suma
as the second operand; the second operand is now 12
i
(21) to a
(12) to get 33 System.out.println(a+++ ++a);
is interpreted the same as
System.out.println(a++ + ++a);
a
as the first operand; the first operand is now 10
a
, its value is now 11a
, its value is now 12a
as the second operand; the second operand is now 12
The problematic System.out.println(a++ +++a);
is interpreted as
System.out.println((a++)++ +a);
which would give the same error when you call post-increment on an integer literal.
In the case of
System.out.println(a++ +++a);
The compiler appears to be interpreting this as
System.out.println((a++)++ +a);
This doesn't work because the result of a pre/post increment/decrement expression is a value, not a variable. (It might also be seeing it as a+ ++(++a)
but the outcome is the same).
Indeed, if you compile this with the Oracle compiler from command line, you get the following error:
UnaryOperatorTests.java:10: error: unexpected type
System.out.println(a++ +++a);
^
required: variable
found: value
1 error
Which is much more indicative of what's going on when compared to the Eclipse compiler's message:
Invalid argument to operation ++/--
That said, you can get that same error from Eclipse by trying to do:
System.out.println(1++);
Adding a space thusly:
System.out.println(a++ + ++a);
seems to remove the ambiguity that confuses the compiler, and compiles as you might expect.
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