Jan
25
For-each loops should define a new variable
Many languages have a for-each loop. In some, like Python, it’s the only kind of for loop:
for i in range(10): print(i) In most languages, the loop variable is only in scope within the code controlled by the for loop,[1] except in languages that don’t have granular scopes at all, like Python.[2]
So, is that i a variable that gets updated each time through the loop or is it a new constant that gets defined each time through the loop?
Almost every language treats it as a reused variable. Swift, and C# since version 5.0, treat it as separate constants. I think Swift is right here (and C# was right to change, despite the backward-compatibility pain), and everyone else is wrong.
However, if there is a major language that should be using the traditional behavior, it’s Python.
for i in range(10): print(i) In most languages, the loop variable is only in scope within the code controlled by the for loop,[1] except in languages that don’t have granular scopes at all, like Python.[2]
So, is that i a variable that gets updated each time through the loop or is it a new constant that gets defined each time through the loop?
Almost every language treats it as a reused variable. Swift, and C# since version 5.0, treat it as separate constants. I think Swift is right here (and C# was right to change, despite the backward-compatibility pain), and everyone else is wrong.
However, if there is a major language that should be using the traditional behavior, it’s Python.