Pages

Saturday, March 19, 2011

Passing a function pointer to a function

#include

int any_function(int(*pfun)(int, int), int x, int y){
return pfun(x, y);
}

int sum(int x, int y){
return x + y;
}

int product(int x, int y){
return x * y;
}

int difference(int x, int y){
return x - y;
}

int main(void){
int a = 10;
int b = 5;
int result = 0;
int (*pf)(int, int) = sum; /* Pointer to sum function */

result = any_function(pf, a, b);
printf("\nresult = %d", result );

result = any_function(product,a, b);
printf("\nresult = %d", result );

printf("\nresult = %d\n", any_function(difference, a, b));
return 0;
}

No comments:

Post a Comment