Hacker News new | ask | show | jobs
by mpartel 1346 days ago
Several languages have or have had this behaviour. C# made a similar change to its 'foreach' loops a long time ago (but not 'for' loops for some reason).

I suppose it's the natural way to do it when implementing a language and not thinking about it too much. It makes a for-loop equivalent to a simple while loop with the loop vvariable initialized outside of the loop.

3 comments

The C# change is described in detail in the linked GitHub issue - one of C# devs left a comment explaining it.

TL;DR is that both "for" and "foreach" scoping fixes would be breaking changes, but "foreach" was easier to justify because it was already a C#-specific construct syntactically, unlike "for" which uses the same exact syntax as C, Java etc, and they were very sensitive to backwards compatibility at the time (esp. since the tooling didn't have the ability to target various language versions within the same project easily). At the same time, "foreach" represented the vast majority of breakage when they looked at existing code, perhaps because the scoping in classic "for" is more obvious due to the fact that variable mutation is explicit there.

To be fair it is no more difficult to implement it with the variable initialized inside of it. In fact, it's easier to.
In c# you mean closure capture?
Almost certainly, that is the vehicle for the issue in most languages.