专访:函数指针VS开关的情况下 [英] Interview : function pointers vs switch case
问题描述
在我的采访中,有人问我实现一个状态机有100个国家,其中依次在每个州有100个事件的系统,我回答以下3个方法:
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
- 函数指针
如果-否则显然是不适合这样的状态机,因此主要比较是的switch-case VS函数指针之间,这里是比较,因为按我的理解:
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:
- 速度明智两者基本相同。
- 切换情况是模块化比函数指针少
- 函数指针有更多的内存开销。
如果能理解上面是正确的人证实?
Could someone confirm if above understanding is correct ?
推荐答案
有可能的函数指针的方法的一个变体,即结构体,它包括一个函数指针以及其他信息。所以,你可以让一个函数处理多个案件。
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.
这篇关于专访:函数指针VS开关的情况下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!