Spoons
Spoons

Reputation: 43

Assign a function pointer passed in as a parameter

Is it possible to pass in a function pointer to a function and have that function assign the function to use?

Below is an example of what I mean:

void sub(int *a, int *b, int *c)
{
    *c = *a + *b;
}

void add(int *a, int *b, int *c)
{
    *c = *a - *b;
}

void switch_function(void (*pointer)(int*, int*, int*), int i)
{
    switch(i){
        case 1:
            pointer = &add;
            break;
        case 2:
            pointer = ⊂
            break;
    }
}

int main()
{
    int a;
    int b;
    int c;
    void (*point)(int*, int*, int*);

    switch_function(point, 1); // This should assign a value to `point`
    a = 1;
    b = 1;
    c = 0;
    (*point)(&a, &b, &c);

    return 0;
}

Any help is appreciated.

Upvotes: 1

Views: 100

Answers (2)

dinoex
dinoex

Reputation: 34

The syntax is much easier if you use a typedef for your function pointer. Especially if you use a double indirection in your sample.

typedef void (*fptr)(int*, int*, int*);

void sub(int *a, int *b, int *c)
{   
    *c = *a - *b;
}

void add(int *a, int *b, int *c)
{   
    *c = *a + *b;
}

void switch_function(fptr *pointer, int i)
{
    switch(i){
        case 1:
            *pointer = &add;
            break;
        case 2:
            *pointer = ⊂
            break;
    }
}

int main()
{
    int a;
    int b;
    int c;
    fptr point;

    switch_function(&point, 1);
    a = 1;
    b = 1;
    c = 0;
    (**point)(&a, &b, &c);

    return 0;
}

Upvotes: 2

Ronan Boiteau
Ronan Boiteau

Reputation: 10138

You can create a pointer to a function pointer.

Here is the syntax:

void (**pointer)(int*, int*, int*);

After you initialized it, you can then dereference this pointer to set your function pointer:

*pointer = &add;
*pointer = ⊂

So your function would look like this:

void switch_function(void (**pointer)(int*, int*, int*), int i)
{
    switch(i) {
        case 1:
            *pointer = &add;
            break;
        case 2:
            *pointer = ⊂
            break;
    }
}

...and you'd call it like this:

switch_function(&point, 1);

Upvotes: 2

Related Questions