1

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?

gosbi
  • 685
  • 1
  • 6
  • 13

1 Answers1

1

Ad for 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 has closures nor lambdas etc., so it's not possible. You have to pass context (ie. the state of variables x1 and x2) yourself, either by adding additional context argument to the function or using global variables.

KamilCuk
  • 96,430
  • 6
  • 33
  • 74