2

I want to make something like this in C:

typedef int (*func)(int);

func make_adder(int a) {
  int add(int x) {
    return a + x;
  }
  return &add;
}

int main() {
  func add_42 = make_adder(42);
  // add_42(10) == 52
}

But this doesn't work. Is it doable? Where is my mistake?

andrepd
  • 587
  • 6
  • 20

1 Answers1

6

No, this is not possible, because there's nowhere in memory where that int a could be stored in such a way that &add refers to it. int a exists on the function stack of make_adder and does not survive, so &add cannot be referring to the original. Making a copy of int a is impossible because the lifetime of that copy would need to be tied to that of &add, and C doesn't have the necessary Garbage Collection for that.

So, in conclusion, we cannot save either the original stack variable a or make a copy on the heap.

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • Thank you. But this code was supposed to be representative of what I want to do, not how would I go about implementing it. Can I implement a functor/closure in C, in any other way, or at least emulate that behaviour? – andrepd Sep 29 '16 at 15:45
  • 4
    @andrepd: Of course you can provide the storage yourself: `struct closure{ int a; int (*fun)(int, int); }` and `int call(struct closure*, int x)`. – MSalters Sep 29 '16 at 15:50
  • Hmm, that makes sense! I guess I was too tied up with the function() syntax that I overlooked the obvious. In C++ I could do that and overload `operator()`, but here I guess that does it ;) – andrepd Sep 29 '16 at 15:55