By Chris Quenelle on Oct 08, 2006
Language geek warning. I'm not going to explain closures here, I'm just going to mumble some thoughts aobut them. Read about them on Wikipedia. The short answer is that a closure is a code-block that you can pass around a pointer to. It lets you write your own replacement for for loops and while loops.
Every now and then I get interested in some language or other that has closures, and I have to figure out what they are again. It's a little bit like not being able to understand pointers in the C language until you can visualize the underlying Von Neumann Architecture underneath. There's no way to understand how closures work until you stop visualizing the traditional call stack architecture.
Since some people started discussing closures in Java recently, I figured I would try to remind myself how they work. My confusion always boils down to "What about global variables?" What happens when a closure access a global variable? I decided to go to my go-to source these days, Wikipedia. Paragraph 2 of the Implementation section says: A typical modern Scheme implementation allocates local variables that might be used by closures dynamically and stores all other local variables on the stack.
All of a sudden it made sense. If you want proper closures, you have to implement a garbage-collected runtime system, and use it for every local and global variable except for cases where the compiler can prove that certain variables cannot be accessed any closures.
So the short answer to my confusion is: You can't have closures in any language that has global variables in the sense that C and C++ have global variables. At least that's my latest understanding.