Usage of pointers to functions
C program to show the usage of pointer to function.
Program
#include<stdio.h>
#include<conio.h>
int sum_func(int x, int y)
{
return x+y;
}
void main()
{
int sum;
// function pointer
int (*fptr)(int, int);
// assign address to function pointer
fptr = sum_func;
printf("Function called normally");
sum = sum_func(10, 20);
printf("\nSum = %d",sum);
printf("\n\nFunction called using pointer");
sum = fptr(20, 30); // calling a function referring to pointer to a function
printf("\nSum = %d",sum);
getch();
}
Output
Function called normally
Sum = 30
Function called using pointer
Sum = 50
Explanation
It is possible to declare a pointer pointing to a function which can then be used as an argument in another function.
A pointer to a function is declared as follows,
data-type (*pointer-name)(parameter);
Here is an example :
A function pointer can point to a specific function when it is assigned the name of that function.
Here 'fptr' is a pointer to a function 'sum_func'. Now, 'sum_func' can be called using function pointer 'fptr' along with providing the required argument values.
A pointer to a function is declared as follows,
data-type (*pointer-name)(parameter);
Here is an example :
int (*sum_func)();
//legal declaration of pointer to function
int *sum_func();
//This is not a declaration of pointer to function
A function pointer can point to a specific function when it is assigned the name of that function.
int sum_func(int, int);
//normal function
int (*fptr)(int, int);
//pointer to function
fptr = sum;
Here 'fptr' is a pointer to a function 'sum_func'. Now, 'sum_func' can be called using function pointer 'fptr' along with providing the required argument values.
fptr(20, 30);