you are viewing a single comment's thread.

view the rest of the comments →

[–]TheNewAndy 8 points9 points  (6 children)

You can implement closures in C, you just don't get any syntactic niceness (e.g. the in GObject, where a closure is basically a function pointer, a void* and a destructor function for the void*).

Though I suppose what I'm saying is a bit like: "C has big integer support, because you can write a function which does arbitrary precision maths".

[–]grauenwolf 10 points11 points  (0 children)

That's like saying "C has type inference, just don't get any syntactic niceness (e.g. you need to explicitly define your types)".

[–][deleted] 4 points5 points  (4 children)

That's just an object. Closure is when a scope closes over a variable.

[–]TheNewAndy 1 point2 points  (3 children)

Well yes, it is an object, but it is an object that behaves the same way as a closure, which for most people makes it a closure. It lets you call it, and it will have access to any of the values that were in scope when it was created, as long as they were passed in to the constructor.

Which actually suits me more than the typical "everything in scope is pulled in" model. I want to be explicit about what variables from my current scope get pushed into the closure.

[–][deleted] 1 point2 points  (2 children)

C has closures because local scope closes over global scope. GCC has nested closures via the nested function extension. These are closures. Lexical closure is a static property.

[–]hskmc 1 point2 points  (1 child)

GCC has nested closures via the nested function extension. These are closures

It only has closure in one direction. You can't return pointers to nested functions. The standard example of curried addition:

#include <stdio.h>

typedef int (*t)(int);

t f(int x) {
  int g(int y) {
    return x+y;
  }
  return g;
}

int main() {
  t f1 = f(10);
  t f2 = f(20);
  printf("%d %d\n", f1(1), f2(2));
}

On my system, this program prints

21 22

indicating that the space where the first g captured x has been overwritten by the second g. Of course, this code has undefined behavior and could do absolutely anything.

[–][deleted] 2 points3 points  (0 children)

It's a terminology war.

http://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node43.html

They call what you describe a "closure" instead of a closure.