C function pointer
Example - Pointing to functions
#include <stdio.h>
/* ww w. jav a 2s . c om*/
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 (*pfun)(int, int); /* Function pointer declaration */
pfun = sum;
result = pfun(a, b); /* Call sum() through pointer */
printf("\npfun = sum result = %d", result);
pfun = product;
result = pfun(a, b); /* Call product() through pointer */
printf("\npfun = product result = %d", result);
pfun = difference;
result = pfun(a, b); /* Call difference() through pointer */
printf("\npfun = difference result = %d\n", result);
return 0;
}
The code above generates the following result.
Example - function as parameter
The following code passes a pointer of a function to another function.
#include <stdio.h>
// w w w.ja v a2 s. c o m
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;
}
The code above generates the following result.