Since Go 1.22, loop {for I, p:= 0, new(int); p = &I; {p = &I}} might never exit
old.reddit.com
old.reddit.com
Swift had the problem in C-style for loops but not in “for…in” loops (https://www.timekl.com/blog/2015/11/26/variable-capture-in-g...), but got rid of it when it removed C-style for loops altogether in Swift 3 (September 2016) (https://github.com/apple/swift-evolution/blob/main/proposals...)
> We have this same problem in for blocks, but for blocks are much looser about what “the loop variable” is; there can be more than one[1. or none at all.] variable declared in the for loop header, it can be incremented in odd ways, and it seems implausible that people would consider each iteration of the for loop to contain a fresh crop of variables. When you say for(int i; i < 10; i += 1) { ... } it seems dead obvious that the i += 1 means “increment the loop variable” and that there is one loop variable for the whole loop, not a new fresh variable i every time through!
> We certainly would not make this proposed change apply to for loops.
List<Action> list = new();
for (var i = 0; i < 10; i++)
list.Add(() => Console.WriteLine(i));
foreach (var action in list)
action();
This (still) prints all 10s. All of the closures are referencing the same "i".I think it is okay to make the change for "for-range" loops, but not okay for traditional "for;;" c-like loops.
This construct seems highly artificial. Perhaps it's an issue in some other less artificial cases, but the change does solve a high number of common errors, so overall it seems like a net win. I don't really see the problem here.
But the change for "for;;" loops has many bad effects.
What the code snippet demonstrates is that, for a contrived scenario, the proposal in question also creates an unexpected result when you expect pointers to remain stable between loop iterations. To be honest, I can't think of any time where this would be an issue for me (as opposed to writing `foo := foo`); Go has quite a bit of cognitive friction in its loop semantics, so anything to reduce unexpected behavior is welcome to my mind.