A program using pointers to functions in C

#include <stdio.h>
 
int main()
{
  int x,y,operation;
  double result, operate(double (*)(),int,int);
  double add(), subtract(), multiply(), divide();
 
  printf("Enter two integers : ");
  scanf("%d %d",&x,&y);
 
  /*Throw away extra character in keyboard buffer*/
  operation=getchar();
 
  printf("Enter an operation (+,-,*,/) : ");
  operation=getchar();
 
  switch(operation)
  {
        case '+': result=operate(add,x,y);
                  break;
        case '-': result=operate(subtract,x,y);
                  break;
        case '*': result=operate(multiply,x,y);
                  break;
        case '/': result=operate(divide,x,y);
                  break;
        default : printf("Invalid option ...");
                  return 0;;
  }
  printf("nThe result is : %gn",result);
  return 0;;
}
 
double operate(double (*pf)(),int a,int b)
{
     double value;
 
     value=(*pf)(a,b);
     return value;
}
 
double add(int p,int q)
{
     return (double)(p+q);
}
 
double subtract(int p,int q)
{
     return (double)(p-q);
}
 
double multiply(int p,int q)
{
     return (double)(p*q);
}
 
double divide(int p,int q)
{
     return (double)(p)/q;
}

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.