Showing posts with label For. Show all posts
Showing posts with label For. Show all posts

Monday, July 28, 2008

WhereFor art thou loop?

So there I was learning this vbScript thingy. I have a problem that requires a for loop. So I start applying logic rather than reading the manual.


For intFoo = 0 To intEndCount Step 1
Wscript.Echo CStr(intFoo) & ". Hello World"
Next
. . .


I fully expected never to greet the world. I am a cave dweller. Why would I? Logic dictates that any lazy parser would read the first line and say unto itself one of two things. Either "intFoo is already equal to intEndCount, therefore I can jump over this redundant code block and get on with my life." This would have been acceptable to me as I really only wanted the for loop to run if intEndCount was bigger than 0.

The other behaviour which would be less acceptable but at least logical would have been "Error 0xFOAD Dumb use of a for loop. Try RTFM and come back to me." (RTFM = Read that Fine Manual) I'd be quite happy to see such a message as this informs the user as to how clever the parser isn't and allows me to dumb down my code appropriately or pick another language.

What I wasn't expecting was this

0. Hello World


I sat there in wonderment. staring at my scratch pad for a full 30 seconds in disbelief. Why loop through once? Your condition has already been met. I tried some variations. Maybe upping the count to 1 would work

For intFoo = 1 To 1 Step 1


Almost the same result. Only the prefixing digit changes. So I go back to TFM. No mention of this strange behaviour. I asked 5 of my colleagues what they would expect. the range of answers went from zero loops, infinite loops, to error state. Nobody guessed that you get one loop out of it. I even went to the Microsoft Fanboi. The guy who likes Vista. He could not explain it. So rather than trying to bust my head on it, my code now features the following statement.

If intEndCount > 0 Then
For intFoo = 0 To intEndCount Step 1
. . .
Next
End If


The trouble is that all the looping functionality in vbScript WORKS THE SAME WAY. I would suggest that having multiple looping statements should give you subtley different functionality.