1

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.

2
  • 1
    In this patricular case, you should return a function pointer. Commented Mar 26, 2018 at 17:50
  • It should really have a default case where pointer is set to NULL on bad input. Better to crash when that pointer is called than to risk calling some actual function. Commented Mar 26, 2018 at 18:40

2 Answers 2

2

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); 
Sign up to request clarification or add additional context in comments.

2 Comments

I think you can also tighten this up a bit more and replace (e.g.) &add with add as the latter is already the address of add
Pointer to function pointer makes perfect sense, thanks for the help.
2

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; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.