Conceptadvanced
Loop variable capture
Also called loop variable capture, closure over the loop variable, closing over the loop variable, loop variable closure, late binding closures, per-iteration loop variable, loopvar, captured loop variable, x := x.
A closure made in a loop captures the loop variable, not its value. If the loop has one variable for all passes, every closure sees the last value. Languages differ, and Go and C# changed their rules.
- Applies to
- core-languages
Idea
A loop makes three functions, one in each pass, and each function should print the number of its pass. In many languages they all print the last number. The functions are closures, and a closure keeps a reference to a variable, not a copy of its value. If the loop has one variable for all passes, all three closures share it, and they see the value that it has when they run, after the loop has ended.
# Each lambda refers to the variable i, not to its value in that pass.
funcs = []
for i in range(3):
funcs.append(lambda: i)
print([f() for f in funcs])
# The variable still exists, so a later change shows in all closures.
i = 10
print([f() for f in funcs])
# A default argument is evaluated when the lambda is made.
funcs = []
for i in range(3):
funcs.append(lambda n=i: n)
print([f() for f in funcs])
# A factory function gives each closure its own variable.
def make(n):
return lambda: n
print([make(i)() for i in range(3)])
[2, 2, 2]
[10, 10, 10]
[0, 1, 2]
[0, 1, 2]
The first loop makes three lambdas that all return 2: they read i when they run, and the loop has left 2 in it. The second line changes i, and all three lambdas see the new value. The default argument n=i copies the value at the time the lambda is made, so each lambda keeps its own number. The factory make gets a new parameter n in each call, so each closure has a variable of its own.
How it works
Closures capture variables. Eric Lippert explains the rule for C#: the lambda ()=>v returns the current value of the variable v, not the value that v had when the lambda was made. In his words, "Closures close over variables, not over values"1. The Python FAQ gives the same reason for its loop of lambdas that all return 16: "x is not local to the lambdas, but is defined in the outer scope, and it is accessed when the lambda is called — not when it is defined"2. See closures.
One variable for the loop, or one for each pass. The result depends on where the language declares the loop variable.
- If the loop has one variable for all passes, the closures share it. The Go blog describes the old rule of Go: three goroutines "are all printing the same variable v"3, so they usually print
cthree times, nota,bandc. - If each pass has its own variable, each closure keeps the value of its pass. In Go, "Each iteration has its own separate declared variable (or variables)"4.
JavaScript: var and let. A var variable belongs to the whole function, so the closures made in a loop share it. MDN shows that a loop with var logs 3, 3, 3, "because variables declared with var are only function-scoped, but not lexically scoped"5. A let in the head of a for loop is special: "A new lexical scope is created with new let -declared variables. The binding values from the last iteration are used to re-initialize the new variables"5. The MDN guide on closures describes the old trap of a loop with var: each closure "shares the same single lexical environment, which has a variable with changing values"6.
C#: foreach changed, for did not. C# 5 moved the variable of foreach into the loop body. Lippert's post starts with the update: "In C# 5, the loop variable of a foreach will be logically inside the loop, and therefore closures will close over a fresh copy of the variable each time. The for loop will not be changed"1. The C# specification now says that "The placement of v inside the while loop is important for how it is captured", and it adds "(Note that earlier versions of C# declared v outside of the while loop.)"7.
Go: the change in Go 1.22. Go made the same change for all its for loops, the three-part loop too. The Go team wanted "to change for loops to make these variables have per-iteration scope instead of per-loop scope"3. In a three-part loop, "The variable used by each subsequent iteration is declared implicitly before executing the post statement and initialized to the value of the previous iteration's variable at that moment"4. The rule depends on the module: "If the language version is go1.22 or later, the module will use the new loop variable semantics"8.
Java: only effectively final variables. Java does not let a lambda capture a variable that changes. "Any local variable, formal parameter, or exception parameter used but not declared in a lambda expression must either be final or effectively final"9. The counter of a basic for loop changes, so a lambda cannot capture it, and the compiler reports an error. The enhanced for loop declares its variable inside the body of the equivalent basic loop, as T VarDeclId = (TargetType) #i.next();10, so each pass has a new variable, and a lambda can capture it.
Rust: a new binding in each pass. A Rust for loop matches each value against its pattern inside the loop: the Reference writes the equivalent code with let PATTERN = next;11 in the body of a loop. Each pass binds a new variable.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Idiom | |
| C++ | Idiom | |
| Java | Native | |
| C | Absent | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript has the loops of JavaScript, so let and const in the loop head give each pass its own binding, and var shares one variable. No example file exists. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | The variable of for (x in xs) is read-only, and a lambda in the body sees the value of its pass. No example file exists because kotlinc is not installed. |
| SQL | Does not apply | SQL has no closures. |
| Bash | Does not apply | Bash has no closures. A function reads the global value of a variable when it runs. |
| PowerShell | Idiom | A script block reads variables when it runs, and the method GetNewClosure() copies them when it is made. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no closures or loops. |
| CSS | Does not apply | CSS has no closures or loops. |
| Regular expressions | Does not apply | A regular expression has no closures or loop variables. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | idiom | one variable for the whole function; a default argument lambda n=i: n or a factory function copies the value |
| JavaScript | native | let and const in the loop head give each pass its own binding; var shares one variable |
| TypeScript | native | the rules of JavaScript; let and const give each pass its own binding |
| Java | native | lambdas capture only effectively final variables; the enhanced for has a new variable in each pass |
| Kotlin | native | the variable of for (x in xs) is read-only, and a lambda in the body sees the value of its pass |
| C# | native | foreach has a new variable in each pass in C# 5 and later; for has one variable for the loop |
| Go | native | a new variable in each pass of every for loop in modules with go 1.22 or later; one shared variable before |
| Rust | native | the pattern of for binds a new variable in each pass; move closures copy or move the value |
| C | absent | no closures; a function pointer with a context argument gets the value as an argument |
| C++ | idiom | a lambda chooses its captures: [i] copies the value, and [&i] refers to the variable |
| Bash | n/a | no closures |
| PowerShell | idiom | a script block reads variables when it runs; GetNewClosure() copies them when it is made |
| SQL | n/a | no closures |
| Regex | n/a | no closures |
| HTML | n/a | no closures |
| CSS | n/a | no closures |
The languages fall into three groups. JavaScript with let, Go, Rust, Kotlin and the foreach of C# make a new variable in each pass, so the closures work as a reader expects. Python, JavaScript with var and the for of C# share one variable, so the program must copy the value. Java and C++ make the programmer choose: Java allows only variables that do not change, and C++ states for each capture if it copies or refers.
The example files show these differences. Python fixes late binding with a default argument and a factory. JavaScript compares var, let and a let outside the loop. Java captures the variable of an enhanced for and a copy of the counter of a basic for. C# compares foreach with for and fixes for with a copy in the body. Go shows that each pass has its own variable and its own address. Rust moves the values into closures and threads. C passes the value to a function with a context argument. C++ compares a capture by value with a capture by reference.
from functools import partial
# A comprehension of lambdas shares one variable too.
fs = [lambda: i for i in range(3)]
print([f() for f in fs])
# A default argument copies the value of each pass.
fs = [lambda i=i: i for i in range(3)]
print([f() for f in fs])
# functools.partial stores the argument when it is made.
def greet(name):
return "hi " + name
calls = [partial(greet, n) for n in ["ann", "bob"]]
print([c() for c in calls])
# Callbacks that run after the loop see the last value.
handlers = {}
for key in ["a", "b", "c"]:
handlers[key] = lambda: key.upper()
print({k: h() for k, h in handlers.items()})
[2, 2, 2]
[0, 1, 2]
['hi ann', 'hi bob']
{'a': 'C', 'b': 'C', 'c': 'C'}
- Verdict: idiom. Python has one variable for each function or comprehension, so all the lambdas of a comprehension read the same
i, and all the handlers read the samekey, after the loop has left"c"in it. The default argumenti=iandfunctools.partialtake the value at the time they are made.
#include <functional>
#include <print>
#include <vector>
int main() {
std::vector<std::function<int()>> by_value, by_ref, init;
// [i] copies the value of each pass.
for (int i = 0; i < 3; i++)
by_value.push_back([i] { return i; });
// [&n] refers to one variable declared before the loop.
int n = 0;
for (n = 0; n < 3; n++)
by_ref.push_back([&n] { return n; });
// An init capture can compute the stored value.
for (int i = 0; i < 3; i++)
init.push_back([sq = i * i] { return sq; });
for (auto* fs : {&by_value, &by_ref, &init}) {
for (std::size_t k = 0; k < fs->size(); k++)
std::print("{}{}", k == 0 ? "" : " ", (*fs)[k]());
std::println("");
}
}
0 1 2
3 3 3
0 1 4
- Verdict: idiom. A C++ lambda lists its captures.
[i]copies the counter, so each lambda keeps its pass.[&n]refers to the one variablen, so all three lambdas see 3 after the loop. A capture by reference of a variable declared in the loop would refer to a dead variable after the pass, which is undefined behavior, so the code capturesn, which lives until the end ofmain.
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
public class Main {
static String run(List<? extends Supplier<?>> fs) {
List<String> out = new ArrayList<>();
for (Supplier<?> f : fs) out.add(String.valueOf(f.get()));
return String.join(" ", out);
}
public static void main(String[] args) {
// The variable of an enhanced for is new in each pass.
List<Supplier<String>> names = new ArrayList<>();
for (String s : List.of("a", "b", "c")) {
names.add(() -> s);
}
System.out.println("enhanced for: " + run(names));
// The counter i changes, so () -> i does not compile.
// A copy in the body is effectively final.
List<Supplier<Integer>> copies = new ArrayList<>();
for (int i = 0; i < 3; i++) {
int copy = i;
copies.add(() -> copy);
}
System.out.println("copy: " + run(copies));
// An array is effectively final, but its element changes.
int[] box = {0};
List<Supplier<Integer>> boxed = new ArrayList<>();
for (box[0] = 0; box[0] < 3; box[0]++) {
boxed.add(() -> box[0]);
}
System.out.println("box: " + run(boxed));
}
}
enhanced for: a b c
copy: 0 1 2
box: 3 3 3
- Verdict: native. Java lets a lambda capture only a variable that is final or effectively final. The variable of the enhanced
foris declared again in each pass, so the lambdas geta,bandc. The counter of a basicforchanges, so the code copies it intocopy. The rule is about the variable, not the object, so a lambda that captures an array reads the element when it runs and sees 3 three times.
#include <stdio.h>
struct job {
int n;
};
typedef void (*callback)(void *ctx);
static void show(void *ctx) {
printf("job %d\n", ((struct job *)ctx)->n);
}
int main(void) {
/* Each callback gets its own context. */
struct job jobs[3];
void *ctxs[3];
for (int i = 0; i < 3; i++) {
jobs[i].n = i;
ctxs[i] = &jobs[i];
}
callback cb = show;
for (int i = 0; i < 3; i++)
cb(ctxs[i]);
/* The trap: one shared context for all callbacks. */
struct job shared;
void *saved[3];
for (int i = 0; i < 3; i++) {
shared.n = i;
saved[i] = &shared;
}
for (int i = 0; i < 3; i++)
cb(saved[i]);
return 0;
}
job 0
job 1
job 2
job 2
job 2
job 2
- Verdict: absent. C has no closures, so a callback gets its data through a context pointer. The first loop gives each callback its own
struct job. The second loop stores the address of one shared struct, so all three callbacks see the last value, which is the same trap as a closure over a shared loop variable.
static string Run(List<Func<int>> fs) => string.Join(" ", fs.Select(f => f()));
// foreach: each pass has its own variable (C# 5 and later).
var fromForeach = new List<Func<int>>();
foreach (var v in new[] { 100, 110, 120 })
{
fromForeach.Add(() => v);
}
Console.WriteLine($"foreach: {Run(fromForeach)}");
// for: one variable for the whole loop.
var fromFor = new List<Func<int>>();
for (int i = 0; i < 3; i++)
{
fromFor.Add(() => i);
}
Console.WriteLine($"for: {Run(fromFor)}");
// The fix for for: a copy declared in the body.
var fixedFor = new List<Func<int>>();
for (int i = 0; i < 3; i++)
{
int copy = i;
fixedFor.Add(() => copy);
}
Console.WriteLine($"for with a copy: {Run(fixedFor)}");
foreach: 100 110 120
for: 3 3 3
for with a copy: 0 1 2
- Verdict: native. This is the example from Eric Lippert's post: with C# 5 and later,
foreachdeclaresvinside the loop, so the three lambdas return 100, 110 and 120. Theforloop did not change, so its lambdas shareiand return 3, the value that ended the loop. A variable declared in the body is new in each pass.
const run = (fs) => fs.map((f) => f()).join(" ");
const withVar = [];
for (var i = 0; i < 3; i++) {
withVar.push(() => i);
}
console.log("var:", run(withVar));
const withLet = [];
for (let j = 0; j < 3; j++) {
withLet.push(() => j);
}
console.log("let:", run(withLet));
// A let declared before the loop is one variable for all passes.
const outside = [];
let k = 0;
for (; k < 3; k++) {
outside.push(() => k);
}
console.log("let outside:", run(outside));
// for...of with const gives each pass its own binding.
const names = [];
for (const name of ["ann", "bob"]) {
names.push(() => name);
}
console.log("for...of:", run(names));
// The old fix: a function call makes a new variable.
const iife = [];
for (var m = 0; m < 3; m++) {
iife.push(((n) => () => n)(m));
}
console.log("factory:", run(iife));
var: 3 3 3
let: 0 1 2
let outside: 3 3 3
for...of: ann bob
factory: 0 1 2
- Verdict: native. A
varcounter belongs to the function, so the three closures read one variable, which is 3 after the loop. Aletin the head of the loop gets a new binding for each pass, but aletdeclared before the loop is one variable again. Beforelet, code called a function in each pass, which gave each closure its own parameter.
package main
import (
"fmt"
"sync"
)
func main() {
// Go 1.22 and later: each pass has its own i.
var prints []func() int
for i := 1; i <= 3; i++ {
prints = append(prints, func() int { return i })
}
for _, p := range prints {
fmt.Print(p(), ";")
}
fmt.Println()
// Each pass also has its own v, at its own address.
var ptrs []*string
for _, v := range []string{"a", "b", "c"} {
ptrs = append(ptrs, &v)
}
fmt.Println(*ptrs[0], *ptrs[1], *ptrs[2], ptrs[0] != ptrs[1])
// A variable declared before the loop is still shared.
var x int
var shared []func() int
for x = 0; x < 3; x++ {
shared = append(shared, func() int { return x })
}
fmt.Println(shared[0](), shared[1](), shared[2]())
// Goroutines get the value of their pass.
out := make([]string, 3)
var wg sync.WaitGroup
for i, name := range []string{"ann", "bob", "cy"} {
wg.Add(1)
go func() {
defer wg.Done()
out[i] = fmt.Sprint(i, "=", name)
}()
}
wg.Wait()
fmt.Println(out)
}
1;2;3;
a b c true
3 3 3
[0=ann 1=bob 2=cy]
- Verdict: native. With
go 1.22or later ingo.mod, the closures of the three-part loop print 1, 2 and 3, and the pointers&vpoint to three different variables. A variable declared before the loop withvar xis not a loop variable, so the closures share it and see 3. The goroutines write to their own slots, so the output has a fixed order. Before Go 1.22, the first loop printed 4 three times.
use std::thread;
fn main() {
// Each pass binds a new i, and move copies it into the closure.
let mut fs: Vec<Box<dyn Fn() -> i32>> = Vec::new();
for i in 0..3 {
fs.push(Box::new(move || i * 10));
}
let vals: Vec<i32> = fs.iter().map(|f| f()).collect();
println!("{:?}", vals);
// Threads get owned values, one in each pass.
let names = vec!["ann".to_string(), "bob".to_string()];
let mut handles = Vec::new();
for (i, name) in names.into_iter().enumerate() {
handles.push(thread::spawn(move || format!("{i}:{name}")));
}
for h in handles {
println!("{}", h.join().unwrap());
}
// A closure that borrows a variable cannot outlive it.
let mut total = 0;
let mut add = |x: i32| total += x;
for x in [1, 2, 3] {
add(x);
}
println!("total {}", total);
}
[0, 10, 20]
0:ann
1:bob
total 6
- Verdict: native. The pattern of a
forloop binds a newiin each pass, and amoveclosure copies the value of that pass. Withoutmove, the closure would borrowi, and the compiler would reject the code, becauseidoes not live as long as the vector. The threads take ownership ofiandname. The last closure borrowstotalmutably, and the borrow ends beforeprintln!reads it.
Variations and related ideas
- Goroutines and threads. A closure that runs later, in a goroutine, a thread or a callback, sees the value of the variable when it runs. The Go blog notes that "Although concurrency is often involved, it need not be"3.
- The copy in the body. In old Go code,
v := vat the start of the body made a new variable for each pass. The Go wiki describes the new rule in these terms: "the effect is as if each loop body starts with k := k and v := v for each range variable"8. - Pointers to the loop variable. Taking the address of a loop variable, as in
&vin Go, has the same problem as a closure. The Let's Encrypt bug in the Go blog came from a pointer, not a closure3. - Tests that pass for the wrong reason. The Go blog shows a test that ran its subtests after the loop, so it checked only the last value, and it passed with an odd number in the list3.
Pitfalls
- Old versions of the language. In Go, "the new semantics will only apply in packages contained in modules that declare go 1.22 or later in their go.mod files"3, so a module with
go 1.21keeps the old rule. C# before version 5 shares theforeachvariable7. The same code can behave in two ways. - The
forloop of C#. C# changed onlyforeach. A lambda that captures the counter of aforloop still sees its last value. varin old JavaScript. Code that usesvarin the loop head, or declares the variable before the loop, shares one variable between all closures, as MDN shows5.- Python comprehensions. A list of lambdas made in a comprehension, such as
[lambda: i for i in range(3)], has the same problem, because all the lambdas share the variable of the comprehension. - Unnecessary copies. Tools that warn about the capture can be wrong. The Go team found many
x := xlines that were not needed, "suggesting instead that popular checkers have significant false positive rates"3.
Cost
A new variable in each pass costs nothing in most loops. The Go wiki says that "A loop only compiles differently if the loop variable has its address taken (&i ) or is captured by a closure"8, and even then the compiler may keep the variable on the stack. "However, in some cases, an extra allocation will be added"8: a closure that must keep three values needs three variables, not one. The Go team ran the new rule in all the builds at Google for months and reported "zero reports of any problems in production code"3.
History
Lippert wrote in 2009 that the capture of the foreach variable was "the single most common incorrect bug report we get"1. He listed the reasons against a change, such as that "obviously this would be a breaking change"1, but C# 5 made it. In Go, "Prior to [Go 1.22], iterations share one set of variables instead of having their own separate variables"4. In 2023 David Chase and Russ Cox wrote that the bug "has caused production problems at many companies"3, and Go 1.22 gave each pass its own variable in modules that declare the new version.
References
- Eric Lippert, Closing over the loop variable considered harmful, part one, 2009, the update at the top; the whole post
- Programming FAQ, Python documentation, Why do lambdas defined in a loop with different values all return the same result?
- David Chase and Russ Cox, Fixing For Loops in Go 1.22, The Go Blog, 2023, The Problem; The Fix
- The Go Programming Language Specification, For statements with for clause
- for, MDN Web Docs, Lexical declarations in the initialization block
- Closures, JavaScript Guide, MDN Web Docs, Creating closures in loops, A common mistake
- Statements, C# language specification, 13.9.5 The foreach statement
- Go Wiki: LoopvarExperiment, How do I try the change?; What is the solution?
- The Java Language Specification, Java SE 25 Edition, Chapter 15, 15.27.2 Lambda Body
- The Java Language Specification, Java SE 25 Edition, Chapter 14, 14.14.2 The enhanced for statement
- Loops and other breakable expressions, The Rust Reference, Iterator loops
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 6TYQCC Edit this page History Report an error Markdown