r/visualbasic • • Oct 20 '16

Reasoning behind backwards loop

I am running some code to look through our bank and match it to our accounting, and i am using a for i=m to 1...next loop - step -1. When i change it to go forward ( step+1) it messes everything up. I've seen this before, but why?

5 Upvotes

4 comments sorted by

View all comments

2

u/chrwei Oct 20 '16

there's a few good reasons for that. removing elements from a queue inside the loop is one, another could be the source data is sorted descending and you want to process it ascending. looping back is more efficient than re-sorting.

a better way to loop over a queue while removing items is a while loop, then you add to the end and remove from the front without issue.