K
Kapil Khosla
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;
}
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;
}