0

I have asked a question here on SO about the use of function pointer and someone has replied giving the example of classic calculator

float Plus    (float a, float b) { return a+b; }
float Minus   (float a, float b) { return a-b; }
float Multiply(float a, float b) { return a*b; }
float Divide  (float a, float b) { return a/b; }

in some way you select your operation

 /* Here there should be an if or a switch/case that selects the right operation */
 float (*ptrFunc)(float, float) = Plus;  

Now here he says "here there should be an if or a switch/case that selects the right operation"

And have read many times function pointer can be used to replace if or switch/case statement but not able to understand (even in this calculator example) how function pointer can replace if or switch/case?

Can anyone help me how do I visualize function pointer replacing if or switch/case.

Amit Singh Tomar
  • 8,380
  • 27
  • 120
  • 199

3 Answers3

5

If you need to call the calculator function more than once, then you only need to decide which function to call once, and then call it as many times as you need.

if (something) {
    ptrFunc = Plus;
} else {
    ptrFunc = Minus;
}

c = ptrFunc(a, b);
z = ptrFunc(x, y);
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
4

He doesn't want you to replace it, he wants you to write one to choose the right operation:

float (*ptrFunc)(float, float);
switch (something)
{ 
  case 1: 
    ptrFunc = Plus;
    break;

     .
     .
     .
}
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
2

Consider something like this:

typedef float (*op)(float a, float b);

typedef struct { 
   char name;
   op implementation;
} operation;

operation ops[] = {
    { '+', Plus},
    { '-', Minus},
    { '*', Multiply},
    { '/', Divide}
};

As you read your input, you find the ops[n].name that matches the operator you got from the input, and call ops[n].implementation.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111