Function Pointers in C and C++
C is one of the most reputed and basic languages in the programming world. So, people are willing to learn this C language as soon as possible.
But, they can only understand if the have clear documentations.
Many readers are getting the wrong concepts from the internet resources.
Here you can get the clear idea about one of the important topics of C language.
We know pointer, which is used to point the particular address. It is mainly used to do some operations based on the address itself.
Like wise, there is one more pointer is there
Function Pointer
1. Before going into the creation of function pointer, just define one function that you want to be pointed by the function pointer.
Ex,
int topoint(int a, int b)
{
return a+b;
}
Now you have defined the function which you want to be pointed by the function pointer.
2. You can create the function pointer by using the following syntax.
Syntax:
return_type (*function_name)(parnameter1_type,parnameter2_type);
Ex,
int (*Funcpoint)(int,int);
3. Now you have successfully created the function pointer, so that lets use it by using the below.
Just assign the function name to the Funcpoint variable as follows:
Funcpoint = topoint;
Usage: int add = Funcpoint(5,10);
From the below program you can get an exact idea about function pointer:
Sample Program
#include <stdio.h>
int (*Funcpoint)(int,int);
int add(int a, int b)
{
return a+b;
}
int main()
{
Funcpoint = add;
int total = Funcpoint(5,10);
printf("TOTAL:%d\n",total);
return 0;
}
OUTPUT: TOTAL:15



Comments