Hi, I'm trying to learn about function pointers and how to use them.
I have the following partially written program in c for a simple calculator, and without using a switch statement, how can I complete it using function pointers?
Code:
//declare functions
float plus(float a, float b) { return a+b; }
float minus(float a, float b) { return a-b; }
float times(float a, float b) { return a*b; }
float divide(float a, float b) { return a/b; }
int main() {
//declare function pointers
float(*fptr_p)(float, float);
float(*fptr_m)(float, float);
float(*fptr_t)(float, float);
float(*fptr_d)(float, float);
//point ptr's to functions
fptr_p=+
fptr_m=−
fptr_t=×
fptr_d=÷
return 0;
}
usually I would get the input from the command line here, and use a switch statement. This is probably the easiest way of doing things, and function pointers need not be used, but I'm sure there is a way of using them for this, and I can't think how. I'm just about familiar withn how to pass a function pointer as an argument of a function and how to return a function pointer from a function, but I can't see how this gets rid of the need for a switch statement.