• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why doesn't the variable get updated in loop?  RSS feed

 
Rezniv Roscky
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Considering following simple loop


I just expected j gets incremented and decremented from 0 to 16 and vise versa, but it's always 0! what am I doing wrong here?
 
Campbell Ritchie
Marshal
Posts: 55781
164
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My, that is hard code to read!
But when I had sorted out the formatting by putting spaces round all your operators, I realised that the whole things boils down to
j = j++;
That never works.
If you search this forum you will find that lots of people get that sort of confusion, and we even have an FAQ about it.
 
Stephan van Hulst
Saloon Keeper
Posts: 7817
142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have fallen into the j = j++ trap. Recall what the postfix increment operator does.

Rezniv Roscky wrote:Considering following simple loop

This is not a simple loop. You really should remove the k and j variables, because it's not immediately clear that the only actual iteration counter is just i.
 
Steffe Wilson
Ranch Hand
Posts: 165
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wow thats an intense loop!
As others already said, problem is with the j++ but just to add that if you do j+1 instead it should do what you expected. (and j-1 correspondingly).
But the code needs restructuring as already stated.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!