title: Finite-State Machine implementation
body: <p>I'm trying to implement Finite-State Machine in C and need it to be very fast.
  So I decided to use function pointers as "states":</p>
  
  <pre><code>void *state1(void){ /* function body here */ }
  void *state2(void){ /* ... */ }
  void *state3(void){ /* ... */ }
  </code></pre>
  
  <p>Then, main FSM loop can be very simple:</p>
  
  <pre><code>void *(*fp)(void);
  fp = state1;
  
  while(fp)
      fp = fp();
  </code></pre>
  
  <p>There is a questions:</p>
  
  <p>1) Is it possible to avoid using void pointer in function return types? Ideally state functions should have some typedef'ed type to ensure that in FSM will be used only functions with this type.</p>
  
  <p>2) Traditional approach of implementing FSM in C is using enum for states and switch-based dispatcher loop, so comparing with function-pointers based implementation there is will be one indirection level. <br>But I'm not sure, can there some issues with instruction-cache or branch prediction have a place? In other words, can there exist implementation that can outperform my solution?</p>
  
  <p>Thanks.</p>