views:

231

answers:

2

How can I use a function pointer instead of a switch statement?

A: 

Here's a page that does a pretty good job of explaining this in C++:

ars
+1  A: 

A slightly different approach from the above link: You can use the value from the switch statement as an array index in an array of function pointers. So instead of writing

switch (i) {
    case 0: foo(); break;
    case 1: bar(); break;
    case 2: baz(); break;
}

you can do this

typedef void (*func)();
func fpointers[] = {foo, bar, baz};
fpointers[i]();

Alternatively you can use the function pointers instead of numbers as described in ars's answer.

stribika