# Function Pointers

Discussion in 'C++' started by Kapil Khosla, Jul 18, 2003.

1. ### Kapil KhoslaGuest

Hi,
I am trying to understand the use of Function Pointers. I wrote a
small to understand the use but am not convinced that it is the
correct implementation.

Can you show me a way to remove the switch statement in this case ?
Thanks,
Kapil

#include "stdafx.h"
using namespace std;

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; }
float Func(float,float);

void Switch_With_Function_Pointer(float,float,float
(*pt2Func)(float,float));
int main()
{

float a,b;
float (*Func)(float,float);
char opCode;
cout << "Enter the numbers and operation" << endl;
cin >> a >> b >> opCode;
// Do I really need this switch ,is there a faster way !!
switch(opCode)
{
case '+' : Func = Plus;
break;
case '-' : Func = Minus;
break;
case '*' : Func = Mult;
break;
case '/' : Func = Div;
break;
}

Switch_With_Function_Pointer(a,b,Func);
return 0;
}

void Switch_With_Function_Pointer(float a,float b,float
(*pt2Func)(float a,float b))
{
float result = pt2Func(a,b);
cout << "Switch with function result is " << result << endl;
}

Kapil Khosla, Jul 18, 2003

2. ### Victor BazarovGuest

"Kapil Khosla" <> wrote...
> I am trying to understand the use of Function Pointers. I wrote a
> small to understand the use but am not convinced that it is the
> correct implementation.

> Can you show me a way to remove the switch statement in this case ?

Put the function pointers into a map<char,double(*)(double,double)>
and extract the required pointer using the opCode as the Key.

> Thanks,
> Kapil
>
> #include "stdafx.h"
> using namespace std;
>
> 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; }
> float Func(float,float);
>
> void Switch_With_Function_Pointer(float,float,float
> (*pt2Func)(float,float));
> int main()
> {
>
> float a,b;
> float (*Func)(float,float);
> char opCode;
> cout << "Enter the numbers and operation" << endl;
> cin >> a >> b >> opCode;
> // Do I really need this switch ,is there a faster way !!
> switch(opCode)
> {
> case '+' : Func = Plus;
> break;
> case '-' : Func = Minus;
> break;
> case '*' : Func = Mult;
> break;
> case '/' : Func = Div;
> break;
> }
>
> Switch_With_Function_Pointer(a,b,Func);
> return 0;
> }
>
> void Switch_With_Function_Pointer(float a,float b,float
> (*pt2Func)(float a,float b))
> {
> float result = pt2Func(a,b);
> cout << "Switch with function result is " << result << endl;
> }

Victor Bazarov, Jul 18, 2003