How to use an array index as an operator?
Such that:
#include
main()
{
char sign[]={\'+\',\'-\'};
int a, b;
a = 12 sign[1] 10
You could use function pointers:
//function:
int addInt(int a, int b) {
return a+b;
}
//define the pointer:
int (*functionPtr)(int,int);
main ()
{
functionPtr sign[5];
sign[0] = &addInt;
int a = 5, b = 8;
//...
int sum = sign[0](a,b);
printf("%d", sum);
return 0;
}
It's a little bit more complicated, and in most simple cases, you would want to use a switch statement to call different functions, but this is a very useful method when dealing with larger, more complex cases.
An example of when I've used arrays of function pointers like this was when developing an image processing application, with vendors providing the algorithms for some pretty special processing.
Their code was proprietry though, and so while we could attain dlls containing functions that could do the processing, we couldn't build it into our code. As any number of these dlls may be required, and we wanted the ability to add-remove functionality without re-compiling the entire system, we needed to be able to read the dlls and manage them. We used a method like above for doing this.