Question Problem with loop -- simple thing?

CathInfo

Member
Joined
Jun 5, 2008
Messages
9
Programming Experience
5-10
VB.NET:
            For nIter = 0 To nNumRecordsToRead
                ReDim Preserve strRows(nIter + 1)
                strRows(nIter) = sr.ReadLine()
            Next nIter

While debugging, I'm getting the following for a reading:
nIter .... 678
nNumRecordsToRead .... 677

I would have thought that to be impossible, since I clearly said "For nIter = 0 to 677"

How can the counter exceed its bounds like that?

Matthew
 
Thread moved.

VB.NET:
            For nIter = 0 To nNumRecordsToRead
                ReDim Preserve strRows(nIter + 1)
                strRows(nIter) = sr.ReadLine()
            Next nIter

While debugging, I'm getting the following for a reading:
nIter .... 678
nNumRecordsToRead .... 677

I would have thought that to be impossible, since I clearly said "For nIter = 0 to 677"

How can the counter exceed its bounds like that?

Matthew

It's not exceeding it's bounds if nNumRecordsToRead equals 678, however you are starting the counter at zero which means you typically would want to go one less than the total number.

Try:
VB.NET:
For nIter = 0 To nNumRecordsToRead - 1
 
Actually, that's the problem.

nNumRecordsToRead is 677, not 678.

So how is the counter going higher than the upper bound?

I didn't think it possible before today, and I've been programming for a long time.

Matthew
 
With nIter equal to 678, does it run the code in the For block or does it skip it and exit the loop?

I can't remember if the For Next loops check at the beginning or end of the loop
 
here's a for loop in a more sensible language (c#):

VB.NET:
for(setup;test;post-loop)

order is: setup, test (run loop if true), post op, test (run loop if true), post op, test(run loop if true)...


now a simple loop:

int i;
for(i = 0; i < 3; i+=1) { }
MessageBox.Show(i);


i set to 0
0 < 3? yes, run loop
i += 1
1 < 3? yes, run loop
i += 1
2 < 3? yes, run loop
i += 1
3 < 3? no. dont run the loop, move on
so can you see how our variable i must always end up larger than the end of the loop? That's how it fails the test and stops the loop.. by going out of range

Now, vb's syntax is a little woolly and hides things, but the same applies.. VB actually uses <= but the logic is the same.. the test will only fail when i reaches a value of 4

For i as Integer = 0 to 3 Step 1


Means that while youre INSIDE the scope of the loop, i will be 0 to 3 inclusive. i.e. for the block of code delimited by the loop, i will only be 0, 1, 2 or 3
But to fail the test and stop the loop, i must be incremented to a value of 4!

VB doesnt bother setting it back afte rthe loop finishes, and indeed, in a lot of cases we dont keep loop variables.. we discard them like i did above. For i as Integer = 0 to 3 .... the variable i has no meaning outside of the loop and will be destroyed. youre only seeing the "problem" because you dimmed your i elsewhere
 
Back
Top