Reputation: 1807
(code examples haven't been tested - just are for example)
I have several declarations like so:
void (* const a[])(void) = {func1, func2};
void func1() {};
void func2() {};
a[0]();
That compiles (if it was real code...) and the should runs func1.
However, if I want to pass arguments such as:
a[0](int 10);
Then I change my declarations:
void (* const a[])(int) = {func1, func2};
void func1(int foo) {};
void func2(int foo) {};
a[0](10);
That also compiles but I get the following warning:
warning: initialisation from incompatible pointer type.
The resulting code also runs fine, but I suspect that the declaration is at fault. I can find several examples on how to build function tables that do not pass parameters but am struggling to find an example that shows how to do it with one.
Upvotes: 1
Views: 728
Reputation: 1
I believe that having typedef
-s for defining signature of functions make the code more readable. So why not:
typedef void signature_t(int);
void foo1(int);
void foo2(int);
const signature_t* funarray[] = { foo1, foo2 };
Upvotes: 2
Reputation: 77400
At the time you initialize a
, func1
and func2
aren't declared, so they have the default type declarations of int ()
. Declare func1
and func2
before initializing a
.
void func1(int);
void func2(int);
void (* const a[])(int) = {func1, func2};
void func1(int foo) {};
void func2(int foo) {};
a[0](10);
Upvotes: 3
Reputation: 14458
Most likely the declarations of func1
and func2
declare them as taking void
as a parameter, rather than taking int
. You probably have
void func1(void);
void func2(void);
in some header file. Instead, you need
void func1(int);
void func2(int);
This is because the declaration
void (*const a[])(int)
means that a
is an array of function pointers taking int
and returning void
.
Upvotes: 3