Function pointer - how to declare function pointer in structure and how it call ,see it.
Code: Cpp
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct strfunptr
{
float a;
float b;
float (*Func)(float,float);
}sfptr;
float Plus(float a, float b)
{
return a + b;
}
float Minus(float a, float b)
{
return a - b;
}
float Mult(float a, float b)
{
return a * b;
}
float Div(float a, float b)
{
return a / b;
}
void Switch_With_Function_Pointer(struct strfunptr *);
int main()
{
sfptr *ptr;
ptr = (struct strfunptr*)malloc(sizeof(ptr));
char ch;
do
{
printf("1.Add \n");
printf("2.Sub \n");
printf("3.Mul \n");
printf("4.Div \n");
printf("Enter the operation Choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1 : printf(" \n Enter the numbers :");
scanf("%f %f",&ptr->a,&ptr->b);
ptr->Func = Plus;
break;
case 2 : printf(" \n Enter the numbers :");
scanf("%f %f",&ptr->a,&ptr->b);
ptr->Func = Minus;
break;
case 3 : printf("\n Enter the numbers :");
scanf("%f %f",&ptr->a,&ptr->b);
ptr->Func = Mult;
break;
case 4 : printf(" \n Enter the numbers :");
scanf("%f %f",&ptr->a,&ptr->b);
ptr->Func = Div;
break;
default :
printf(" \n Invalid Choice :");
exit(0);
}
Switch_With_Function_Pointer(ptr);
}while(1);
return 0;
}
void Switch_With_Function_Pointer(struct strfunptr *funptr )
{
float result = funptr->Func(funptr->a,funptr->b);
printf("Switch with function result is :%f\n",result);
}

