The syntax for declaring a function pointer:
void (*foo)(int);
foo is a pointer to a function taking one argument, an integer, and that returns void
Complex Case:
void *(*foo)(int *);
Here, the key is to read inside-out; notice that the innermost element of the expression is *foo, and that otherwise it looks like a normal function declaration. *foo should refer to a function that returns a void * and takes an int *. Consequently, foo is a pointer to just such a function
Initializing and Using Function Pointers
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <stdio.h> void myfunc(int x) { printf( "%d\n", x ); } int main() { void (*foo)(int); foo = &myfunc; /*the ampersand is actually optional */ foo = myfunc /* call my_int_func (note that you do not need to write (*foo)(2) ) */ foo( 2 ); return 0; } |
Function Pointers can be ideally used to implement Callback:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <stdio.h> int add(int x,int y) { return x+y; } int sub(int x,int y) { return x-y; } void calculateandprint(int a,int b,int (*operation)(int,int)) { int res = operation(a,b); /*Will call function whose pointer is passed to it by main.*/ printf("Result: %d",res); } int main() { int (*op)(int,int); op = sub; calculate(10,20,op); return 0; } |
void pointer:
- The void keyword is used to specify that a function either doesn’t take arguments or doesn’t return a value. The void keyword can also be used to create a generic pointer–a pointer that can point to any type of data object.
- For example, the statement
void *x;
declares x as a generic pointer. x points to something; you just haven’t yet specified what
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
#include <stdio.h> int n; double d; void* add_int(void *px,void *py) { int *p1 = (int*)px; int *p2 = (int*)py; n = (*p1 + *p2); return &n; } void* add_double(void *px,void *py) { double *p1 = (double*)px; double *p2 = (double*)py; d = *p1 + *p2; return &d; } void* processing(void *pa,void *pb,void* (*operation)(void*,void*)) { //... void *res = operation(pa,pb); //.... return res; } int main() { void* (*op)(void*,void*); op = add_double; double n1,n2; n1 = 10;n2 = 20; double *pd =(double*)processing(&n1,&n2,op); printf("%f",*pd); op = add_int; int m1,m2; m1 = 10,m2 = 5; int *pm = (int*) processing(&m1,&m2,add_int); printf("%d",*pm); return 0; } |