Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interview : function pointers vs switch case

During my Interview, I was asked to implement a state machine for a system having 100 states where each state in turn has 100 events, I answered 3 following approaches:

  • if-else
  • switch-case
  • function pointers

If-else is obviously not suited for such a state machine, hence main comparison was between switch-case vs function pointers, here is the comparison as per my understanding:

  • Speed wise both are almost same.
  • Switch-case is less modular than function-pointers
  • Function-pointers has more memory overhead.

Could someone confirm if above understanding is correct ?

like image 963
user1897724 Avatar asked Dec 12 '12 12:12

user1897724


1 Answers

There might be a variant of the function pointer approach: a struct which includes a function pointer as well as other information. So you could let one function handle several cases.

Beside of this, I think you are right. Plus, I would consider the overhead concerning memory and speed worth to be considered, but hopefully small enough to be ignored at the end.

like image 105
glglgl Avatar answered Sep 23 '22 23:09

glglgl