Saturday 3 December 2016

Function Pointer Advance

Passing Function pointer to another function

It this blog we discuss how to pass function pointer to another function.
In C it is possible to pass the function pointer in functions. In this we directly pass the address of another function in one function call. Example of function pointer declaration with passing function pointer:

int (*funptr2)(int, char, void  (*funptr1)(void));   

this function pointer accept a void function pointer, one integer, one char and return a integer value.We will understand this by taking the example of performing math operation using with function pointer. We proceed with last blog example.

/*********function Declaration**********/
int ADD_2_Number(int x, int y);
int SUB_2_Number(int x, int y);
int MUL_2_Number(int x, int y);
int DIV_2_Number(int x, int y);
int math_operation(int (*funpoiter1)(int,int),int x,int y);

/*********Function Definition***********/
int ADD_2_Number(int x, int y){ return (x+y);}
int SUB_2_Number(int x, int y){ return(x-y);}
int MUL_2_Number(int x, int y)   { return(x*y);}
int DIV_2_Number(int x, int y)   { return(x/y);}

int math_operation(int (*funpoiter1)(int,int),int x,int y)
{
    return((*funpoiter1)(x,y));
}

math_operation function will accept the function pointer for math operation to be performed and two variable on which operation has to be performed.

Function Pointer Declaration

int (*Funptr1)(int, int);         //Function pointer Declaration
int (*Funptr2)(int, int);         //Function pointer Declaration 
int (*Funptr3)(int, int);         //Function pointer Declaration
int (*Funptr4)(int, int);         //Function pointer Declaration
int  (*Funptr5)(int (*Funptr6)(int,int),int,int );
//function pointer declaration for math_operation //function

Assigning function address to function pointer  

Funptr1 = &ADD_2_Number;  //assign ADD_2_Number address to Funptr1
Funptr2 = &SUB_2_Number;  //assign ADD_2_Number address to Funptr2
Funptr3 = &MUL_2_Number;  //assign ADD_2_Number address to Funptr3
Funptr4 = &DIV_2_Number;  //assign ADD_2_Number address to Funptr4
Funptr5= &math_operation;// assign math_operation address to Funptr4

Call math_operation function using Function pointer

RESULT =  (* Funptr5)((*Funptr1),34,35);

In this statement Funptr5 point to the math_opration function, Funptr1 point to ADD_2_Number function and passes two number 34 and 35 which has to be added. Similiary other math fnction can be performed.
RESULT =  (* Funptr5)((*Funptr2),89,34);
RESULT =  (* Funptr5)((*Funptr3),34,12);

RESULT =  (* Funptr5)((*Funptr4),666,6);

No comments:

Post a Comment