• Post Reply Bookmark Topic Watch Topic
  • New Topic

increment operator  RSS feed

 
Brian King
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I'm confused why the following code leads to x being 1 when it's printed out.  Can someone explain what the program is doing that would seem to cause it to loop back and change x = 0 after ++x? 

Thanks.

 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
People usually get confused the other way round, why...prints 3 rather than 4.
It is really simple: the ++i operator causes the entire expression to take the value of the new value of i, in this case 1. You have incremented x (line 6) before printing it (line 9), and then assigned the new value to z, so both variables have the new value of 1.
If you want x to be unchanged, you will have to write something like
int z = x + 1;
 
Brian King
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for always helping Campbell!
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's a pleasure

And thank you for the pie
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!