Loop Variables

A subscriber to my Real Studio training videos sent me an email the other day asking me why I did something in the videos.  He was asking why I did this

for i as integer = 0 to ar.ubound

rather than

dim i as integer

for i = 0 to ar.ubound

I had no real answer except that it’s a little less typing and that the variable, i, can’t be used outside of the for next loop.

The subscriber went on to say that he tested both for speed and that there’s essentially no difference between the two versions.  That has been my experience too.

I initially was very against this ‘shorthand’ method.  It was introduced to me by my senior developer, Seth, and it just looked…odd.  I think at one point I might have even emailed him to ask him to stop doing it.  After a brief discussion he convinced me it didn’t matter to him but if I really wanted him to go back to the other method he could.

To make a long story short, I tried it out for a week and I discovered that I really prefer it to the other way and I’ve used it consistently ever since.  It’s a bit less typing.  I don’t know about you but I am essentially a lazy programmer so anything that means less typing is good for me.

The second reason is that when you declare the variable in the for next loop the variable is local only to the loop.  This means I can’t reuse it outside of the loop by accident.  If I declare the variable outside the loop I can use it again (sometimes by accident).  Of course, there are times you actually WANT to reuse the variable but I find those rare.

The other thing that I tend to do is reuse the same loop variable time and time again even in the same method.  So I get code like this:

for i as integer = 0 to ar.ubound
   //Do something in this loop

//Some other code

for i as integer = 0 to iMax
   //Do something in this loop

//Wrap up the function

I find this to be very readable (though I’m not doing anything in these examples). ‘i’ is my default loop variable and I think I’ve had entire apps where my only loop variable is i even though I’ve had thousands of for next loops.

Anyway, given the recent discussion on standards, I thought I’d ask what you do?  Do you have a preference?  Do you despise one over the other?  Does it really matter to you?

Happy coding!