|Keep It Simple, Stupid|
Re^3: Repeating Code - there has GOT to be a better way!by GrandFather (Sage)
|on Mar 31, 2010 at 20:14 UTC||Need Help??|
There is an excellent reason why you should always use my to declare a for loop variable in the loop - a for loop variable isn't what you think it is! Consider:
What do you expect to see printed? What do you actually see printed? Now try this:
What do you expect to see printed? What do you actually see printed?
A for loop variable is aliased to each element of the for list in turn. When you use a previously declared variable as the loop variable you are really only using the name, the value is untouched.
So, always declare your for loop variable in the loop header because it ain't what you think it is anyway and declaring it make sure everyone gets that idea.
Note that a C style for loop is different and there it does often make sense to use a variable from the scope global to the loop.
True laziness is hard work