Pages

Tuesday, 25 April 2017

Function Pointer



   Function pointer is a type of pointer which points a function or code block. You can assign address of a function to function pointer variable and that function using function pointer variable name.


   I have a bad experience while making Calculator. In my design all the calculation takes place when user pressed equal button. When a user pressed equal button I need to check every time which operator user was pressed , checked by switch case, it become complicated then I increase more function in my calculator because of lots condition for operator check and attached code for particular logic separately.


   Now my work becomes simple because of function pointer because I just need to check operator pressed by user and attached related function code to function pointer. It reduces lots of condition checking and assigns separate code to each section. So function pointer is very useful in some specific scenario.


Advantage of function pointer

  • Implement Callback
  • Useful in event handling
  • One entry point for more than one code block

void (*p1)();

P1 point a function which doesn’t take argument nor return a value. () is use to declare pointer variable because without using bracket it will tell compiler that function will return address of some memory location.

void *p1();

One you have created your function pointer then after you need assine function address to Pointer variable.

 p1=&fun1;

fun1 must be a function name and doesn’t take any argument nor return a value. After assign function address to function pointer variable its time to call that function using pointer variable.

     p1=&fun1;
     p1();

This is the way from which you can call the fun1 function using p1 poniter variable.

void fun1()
{
     printf("\n\tFunction without argument");
}
void main()
{
 void (*p1)();
     p1=&fun1;
     p1();
}


Pointer to a function which takes argument


void fun2(char *str)
{
     puts(str);
}
void main()
{
 void (*p2)(char*);
 p2=&fun2;
 p2("\n\tFunction with argument");

}

Pointer to a function which takes and returns arguments


int sum(int a,int b)
{
     return(a+b);
}
void main()
{
int (*p3)(int,int);
printf("\n\tSum of 5+5=%d",p3(5,5));
}

Pointer to a function with array


int sum(int a,int b)
{
     return(a+b);
}
int sub(int a,int b)
{
     return a-b;
}
int mul(int a,int b)
{
     return a*b;
}
void main()
{
int (*p4[3])(int,int);
int (*p4[])(int,int)={fun1,fun2,fun3};
int a,b;
p4[0]=∑
p4[1]=⊂
p4[2]=& mul;
printf("\nEnter first number>> ");
scanf("%d",&a);
printf("Enter Second number>> ");
scanf("%d",&b);
printf("\n\tSum of %d and %d is %d",a,b,p4[0](a,b));
printf("\n\tSubtraction of %d and %d is %d",a,b,p4[1](a,b));
printf("\n\tMultiplication  of %d and %d is %d",a,b,p4[2](a,b));
}



No comments:

Post a Comment