• Post Reply Bookmark Topic Watch Topic
  • New Topic

Unary Operators  RSS feed

 
Jeyakumar Balasubramanian
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As your suggestion


this should print 2. But instead it prints 1. That's where I wondered.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Layne,
Yeah, Your interpretation works well Thanks
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!