Question

I want to pass a function with arguments as argument into some other function, but I don't know how (or if) I can do that.

What I want to do is:

#include <stdio.h>

void getInput(char* request, int (*func)());

int main()
{
    double input;
    getInput("Input: ", scanf("%lf", &input));
}

void getInput(char* request, int (*func)())
{
    // do stuff
    func()
    // do more stuff
}

Unfortunately this doesn't work. I think the scanf is getting executed when I'm trying to pass it as an argument. How do I get this to run in getInput?

Was it helpful?

Solution

You can't do that in C, the language doesn't support such a construct.

You can often solve this exact type of problem using variable-arguments functions again:

void getInput(const char *request, const char *fmt, ...)
{
  va_list args;
  printf("%s: ", request);
  fflush(stdout);
  va_start(fmt, args);
  vscanf(fmt, args);
  va_end(args);
}

Usage is like this:

int main(void)
{
  double input;
  getInput("Input", "%lf", &input);
  return 0;
}

Of course you might want to add proper return-value handling, otherwise it's impossible to know if the embedded vscanf() succeeded so the variable is OK to use.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top