Function Pointers

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;
}
 
V

Victor Bazarov

Kapil Khosla said:
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.

Your implementation is fine.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top