hakeris1010
hakeris1010

Reputation: 295

C - Passing function with unknown params to another function, and calling it

I'm trying to achieve something like this:

void sum(int a, int b){ printf("result: %d", a+b); }

void callFunc(void (*funct)(...), ...)
{
     va_list ars;

     va_start(ars, funct);
     funct(ars);
     va_end(ars);
}

int main()
{
     callFunc(sum, 2,3);         

     return 0;
}

But this doesn't work, because of needing of two va_lists, for funct params and arguments passed. However, even if i try to pass the sum function, it says:error: invalid conversion from 'void (*)(int, int)' to 'void (*)(...)'

So how to make this work good old C-style?

Upvotes: 1

Views: 74

Answers (1)

Cornstalks
Cornstalks

Reputation: 38218

You can't do it like that. It's just simply not possible.

The best you can do (while keeping it generic) is change funct to take a va_list, much like vprintf. But that probably won't work very well for your purposes.

Alternatively, you can do a macro:

#include <stdio.h>

#define CALL_FUNC(func, ...) func(__VA_ARGS__)

void sum(int a, int b){ printf("result: %d", a+b); }

int main()
{
     CALL_FUNC(sum, 2, 3);         

     return 0;
}

Upvotes: 3

Related Questions