C – Pointer to Function

Pointer to function: Function has address that we can assign to pointer variable by which we can invoke the function.

Syntax:           <return_type> (*<ptr_name>)(args_list);
 
Example:        int (*fptr)(int,int);
 
Where: “fptr” is a pointer that points to a function which is taking 2 integers and return integer.
int add(int,int);
int sub(int,int);
int main()
{
            int r1, r2, r3, r4;
            int (*fptr)(int,int);
            r1=add(10,20);
            r2=sub(10,20);
            printf(“r1 : %d\nr2 : %d\n”,r1,r2);
           
            fptr = &add; /*pointing to add function*/
            r3=fptr(30,50);
 
            fptr = &sub; /*pointing to sub function*/
            r4=fptr(30,50);
            printf(“r3 : %d\nr4 : %d\n”,r3,r4);
            return 0;
}
int add(int x, int y)
{
            return x+y;
}
int sub(int x, int y)
{
            return x-y;
}
Scroll to Top