Example of call function by Function Pointer
Hi friends
in this blog i will discuss about function call by function pointer by take
example of performing simple arithmetic operation (Addition, Subtraction, Multiplication
and Division) o two numbers. We will discuss this example by dividing function in
four simple 5 steps:
- Function Declaration
- Function Definition
- Function Pointer Declaration
- Assigning Function address to Function Pointers
- Call Function by Function Pointer
Function Declaration
When we
declare any function we tell the compiler about function name, function return
type and passing parameters to function. Following lines declare the function
for ADD, SUB, MUL and DIV.
/*********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);
Function Definition
Function definition
explains the working of function. In Function definition we implement the actual working of function.
/*********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);
}
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
in above lines
we have declare four function pointers Funptr1, Funptr2, Funptr3, Funptr4 with
return types and parameters according to parameter list passing to function ADD_2_Number,
SUB_2_Number, MUL_2_Number, DIV_2_Number.
Assigning Function address to Function Pointers
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
Call Function by Function Pointer
RESULT1 = (*
Funptr1)(34,67);//add function call by
function pointer
In this we
call the ADD_2_Numbers by function pointer Funptr1. Result of addition will be
stored in RESULT1 variable. Where RESULT1 is an integer type variable. Similarly
we can call all other function using function pointer.
RESULT2 =(* Funptr2)(89,12);//sub function call by function pointer
RESULT3 =(* Funptr3)(89,2);//mul function call by function pointer
RESULT4 =(* Funptr4)(525,5);//div function call by function pointer
Thanks for reading this Blog!!!!!!
No comments:
Post a Comment