voltnor voltnor - 3 months ago 19
C Question

Set a function argument with function pointers

In C is there a way to set a function argument using function pointers such that all calls to that function pointer just use the set parameter? As an example, is it possible to do something like the code below?

void do_something(int *a, int *b, int *c){
*a = *c - 5;
*b = *c - 10;
}

typedef void (*funcptr)(int *a, int *b, int *c);

int main(){
int num = 5;
funcptr f = do_something(c=&num); // c = 5 for all calls to f(a, b)
int *a; int *b;
f(a, b); //a = 0, b = -5

num = 10;
f = do_something(c=&num); // c = 10 for all calls to f(a, b)
f(a, b); //a = 5, b = 0
}


This seems possible with external C libraries like Blocks and FFCALL, but it appears I'd need to set a, b, and c instead of setting a single argument.

Answer

Rather than using function pointers, you would need a wrapper function that uses a global for state.

void do_something(int *a, int *b, int c){
    *a = c - 5;
    *b = c - 10;
}

static int c_val = NULL;

void do_something_wrap(int *a, int *b)
{
    do_something(a, b, c);
}

int main(){
  int num = 5;
  c_val = num;
  int *a; int *b;
  do_something_wrap(a, b); //a = 0, b = -5

  num = 10;
  c_val = num;
  do_something_wrap(a, b); //a = 5, b = 0
}