D: Not real closures

September 11th, 2007 Leave a comment Go to comments

This is an example program that shows that D delegates are not real closures. The program should print a countdown starting at ten and stopping at zero. In reality the program enters an eternal loop printing bogus values, showing that delegates don’t keep the bound variables of the environment alive, which is what defines a true closure.

import std.stdio;

int delegate() countdown(int from)
  int current = from;
  int countdown_helper() {
    return current--;

  return &countdown_helper;

void main() {
  int delegate() dg = countdown(10);
  int i;
  do {
    i = dg();
  } while(i > 0);
  return 0;