Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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


2 Answers

A slightly different approach from the link posted by ars: 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.

like image 156
stribika Avatar answered Nov 24 '25 22:11

stribika


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

  • http://oopweb.com/CPP/Documents/FunctionPointers/Volume/CCPP/FPT/em_fpt.html

EDIT:

Above link is broken as of June 2020. Cached here:

https://web.archive.org/web/20170606042951/http://oopweb.com/CPP/Documents/FunctionPointers/Volume/CCPP/FPT/em_fpt.html

like image 36
ars Avatar answered Nov 24 '25 23:11

ars



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!