programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Unary Operators

Jeyakumar Balasubramanian
Greenhorn
Posts: 8
Hi Folks,
We all know that the expression a = b++ is equivalent to
. But I found this concept fails for the expression a = a++. It always produce the result of a, no matter we give the same expression for a number of times. The same thing will be happened for -- operator too.
I'm confused by this result. I don't know whether my understanding is wrong, or any mistery behind that thing. Anybody knows the reason?

Hentay Duke
Ranch Hand
Posts: 198
Assignment happens first, so in this case
a = a++;

a is assigned to a and then incremented by one.

run this and see what happens

[ September 20, 2005: Message edited by: Hentay Duke ]

Jeyakumar Balasubramanian
Greenhorn
Posts: 8

this should print 2. But instead it prints 1. That's where I wondered.

fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
i = 1;
i = i++;

The expression is evaluated first. so the Right hand side evaluates to 1. Now, the ++ operator fires, incrementing i to 2.

Last, assign THE VALUE OF THE EXPRESSION, which we already figured out was 1, to i. so i gets reset from 2 back to 1.

Hentay Duke
Ranch Hand
Posts: 198
You're still assigning 1 to i. If you want to have i incremented just use i++, not i = i++.

I'm sure someone else can give you the technical reason for this behaviour. See Fred's response above which gives a clear explanation.
[ September 20, 2005: Message edited by: Hentay Duke ]

Layne Lund
Ranch Hand
Posts: 3061
Originally posted by Jeyakumar Balasubramanian:
Hi Folks,
We all know that the expression a = b++ is equivalent to
. But I found this concept fails for the expression a = a++. It always produce the result of a, no matter we give the same expression for a number of times. The same thing will be happened for -- operator too.
I'm confused by this result. I don't know whether my understanding is wrong, or any mistery behind that thing. Anybody knows the reason?

It might help if you use a different interpretation of a = b++. It is actually closer to this:

If you use this interpretation, you should be able to understand why a = a++ behaves the way it does.

HTH

Layne

Jeyakumar Balasubramanian
Greenhorn
Posts: 8
Layne,
Yeah, Your interpretation works well Thanks