Aug 10, 2014 at 1:49pm UTC
I want to call different functions depending on the value of an integer without having a huge if...then tree. I don't really have any code yet because I'm at a loss as to what I need to do. Any help?
Aug 10, 2014 at 2:32pm UTC
Are the possible values a continuous range?
If yes, then an array of function pointers is feasible.
Aug 10, 2014 at 8:20pm UTC
You can have an array of function pointers which you can then use to call the respective functions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
#include <iostream>
using namespace std;
void func1 ()
{ cout << "func1" << endl;
}
void func2 ()
{ cout <<"func2" << endl;
}
void func3 ()
{ cout << "func3" << endl;
}
typedef void (*func_ptr_t)();
func_ptr_t func_tbl [3] =
{ func1,
func2,
func3,
};
int main ()
{ for (int i=0; i<3; i++)
(*func_tbl[i])(); // Call the function through the table
system ("pause" );
}
Last edited on Aug 10, 2014 at 8:20pm UTC