IT lexicon › Programming › Closure conversion

Closure conversion

Programming På svenska → Updated: 2026-11-05

The compiler turns every function with free variables into a pair: a plain code pointer and a record holding the captured values.

Machine code only understands functions that get everything through their arguments. A closure reading n from its surroundings therefore has to carry n along somehow. After conversion, every function takes a hidden extra argument — its environment — and every closure becomes a small struct with a pointer to the code plus the captured variables. Calling an unknown function becomes: load the code pointer from the record, call it with the record as first argument.

Andrew Appel's Compiling with Continuations (1992) laid out how SML/NJ does it, including the choice between flat environments, which copy the values, and linked ones, which point on to the enclosing function's environment. Escape analysis then decides whether the environment can live on the stack or must go on the heap. C++ lambdas are the same transformation, performed visibly in the type system.

← Back to the lexicon