A slightly different approach from the link hosted by ars: you can use the value from the switch statement as the index of the array in an array of function pointers. Therefore, instead of writing
switch (i) {
case 0: foo(); break;
case 1: bar(); break;
case 2: baz(); break;
}
You can do it
typedef void (*func)();
func fpointers[] = {foo, bar, baz};
fpointers[i]();
Alternatively, you can use function pointers instead of numbers, as described in ars answer.
source
share