Let's say I have a function
int myfun (int arg1, int arg2, int arg3, int arg4) {
/* function body */
}
and I would like to write a function pass_last_elements()
that has signature
int (*)(int, int) pass_last_elements(int (*myfun)(int, int, int, int), int x3, int x4);
and returns a function of two arguments, let's call it fun_out
, such that fun_out(x1, x2)
computes the same result as myfun(x1, x2, x3, x4)
.
Is it possible to do this purely in C? If not, would it be possible to do it using some compiler extensions?
As for the function signature, you put the function identifier "inside":
int (* pass_last_elements(int (*myfun)(int, int, int, int), int x3, int x4) )(int, int);
As to:
returns a function of two arguments, let's call it fun_out, such that fun_out(x1, x2) computes the same result as myfun(x1, x2, x3, x4)
C language does not have closures nor lambdas etc., so it's not possible. You have to pass context (i.e. the state of variables x1
and x2
) yourself, either by adding a context argument to the function (like cookie
in fopencookie
or arg
in qsort_r
) or using global variables,