I'm currently learning C, and trying to make my code more readable and easy to write, I found myself in need of creating a function (closure) in a function, and returning that function. Here's what I'm trying to do:
#typedef int (int_predicate*)(int);
int_predicate equals(int x) {
int ret(int y) { return x == y; }
return ret;
}
Now, this, doesn't work, and I get it: I'm creating this closure (ret) inside a function, so once this function returns, the pointer is no longer relevant, because it was defined on the stack. This is similar to if I did it for a pointer for a simpler type:
int* bad_int_ptr_function() {
int intOnTheStack;
int* ptr = &intOnTheStack;
return ptr;
}
So, how can I achieve what I want - creating a closure in a function and returing it? If the size of the type pointed at, was known, I'd be able to use malloc
, and if I wanted to, I could follow it with a memcpy
. But, I can only presume that the size of a function can't be found with a sizeof
, because a function can have any number of lines.
This is C, I can't use syntax or libraries that are specific to C++ (I've heard C++ recently-ish got lambda expressions - if only I could use C++, but I can't, this if for a C-specific course).