1

I'm writing some code which should use math function (from math.h) chosen by user. I have something like

printf("If you want to use sin, press 's'\n"
       "If you want to use cosh, press 'c'\n");
do choice = getchar();
while (choice != 's' && choice != 'c');

How to store the function user chose? I would like to have it in some variable fun and then just use it in computation by writing fun(x), but have no idea how to do this. Please, help!

2 Answers2

1
double (*proc)(double x) = NULL;
if (choice == 's') proc = sin;
else if (choice == 'c') proc = cosh;
// ...

double y = proc(x):
Niklas R
  • 16,299
  • 28
  • 108
  • 203
  • Thanks! I've heard about function pointers but I didn't know I can use them to functions from libraries. –  Dec 08 '12 at 17:15
0

You need function pointers. Function pointers are like pointers to code that you can execute. So, for example, you can have a function pointer that takes all functions that take one double and return one (eg. sin, cos, sqrt, tan, arctan, etc.). In these sorts of menu scenerios, using an array is usually best:

double (*funcs)(double)[] = {&sin, &cosh}
char choice;
printf("If you want to use sin, press '1'\n"
       "If you want to use cosh, press '2'\n");
do choice = getchar();
while (choice != '1' && choice != '2');
char choice2[2] = {choice, '\0'};
funcs[atoi(choice2)-1](operand);
Linuxios
  • 34,849
  • 13
  • 91
  • 116