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

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

+3
source share
2 answers

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.

+5
source

Here is a page that explains this pretty well in C ++:

+3
source

Source: https://habr.com/ru/post/1712643/


All Articles