Jayy
Jayy

Reputation: 14728

C pointer to multiple functions

I want to pass to a function a pointer that can point to one of several functions.

What is the syntax for this?

void func_a(char c){
    //
}
void func_b(char c){
    //
}

void receiver(void (*function_pointer)()
{
    // do stuff with the pointer to the function, e.g. call it:
    function_pointer('a');
    function_pointer('b');
    function_pointer('c');
}

void main(){
    receiver(&func_a); // calls func_a with 'a', then 'b', then 'c'
    receiver(&func_b); // calls func_b with 'a', then 'b', then 'c'
}

Will the above work as expected? I assume a function pointer can only be used for functions with the same signature?

Upvotes: 2

Views: 2008

Answers (3)

Praneeth Rao
Praneeth Rao

Reputation: 11

Function pointer to select one function among multiple functions

#include <stdio.h>
int plus(int a,int b){return a+b;}
int minus(int a,int b){return a-b;}
int multiply(int a,int b){return a*b;}
int divide(int a,int b){return a/b;}
int percentage(int a,int b){return a%b;}
void gec(int(**p)(int ,int),int c)
{
c=c%5;
if(c==0)
*p=plus;
else if(c==1)
*p=minus;
else if(c==2)
*p=multiply;
else if(c==3)
*p=divide;
else
*p=percentage;
}
int main(void) {
int a=100,b=20,c=12,r;
int(*fptr)(int,int)=NULL;
gec(&fptr,c);
r=(*fptr)(a,b);
printf("%d",r);
return 0;
}

Upvotes: 1

ezPaint
ezPaint

Reputation: 152

One thing you can do to make this cleaner is use a typedef. Define your function pointer in a typedef and you can use it in the arguments. Also you don't need the &. Example with your code.

#include <stdio.h>

static void func_a(char c)
{
        printf("a:%c\n", c);
}

static void func_b(char c)
{
        printf("b:%c\n", c);
}

typedef void (*function)(char c);

void receiver( function func )
{
        func('a');
        func('b');
        func('c');
}

void main()
{
        receiver(func_a);
        receiver(func_b);
}

I learned this from 'learn C the hard way' link: http://c.learncodethehardway.org/book/ex18.html

Upvotes: 2

unwind
unwind

Reputation: 399833

Yes, that looks like it should work.

And yes, you can only use the single pointer for functions sharing a signature.

Minor notes:

  • You don't need to use & to take the address of a function, the function's name evaluates to its address in suitable contexts.
  • Functions that are local and only intended to be used as callbacks (func_a() and func_b()) should be declared as static.

Upvotes: 3

Related Questions