S
sqweek
Hiya. I've just been implementing a finite state machine a couple of
times to compare the performance of different approaches. One of my
attempts was to have a function for each state, which takes a single
character of input and returns a function pointer to the next state.
This presented an interesting challenge when I tried to code it.
"typedef statefn* (statefn)(int);" is the closest I've got, but of
course you can't refer to the new type within the typedef itself.
I ended up just returning void* and noted this implementation was
terrible[1] compared to the switch and goto solutions, but it's nagging
me that I didn't work out how to define the function properly.
So... is it possible?
(I found a C++ solution at http://www.gotw.ca/gotw/057.htm but nothing
in straight C)
[1] Mind you, my state machine only had 3 states, so the advantage of
the function method has of jumping straight to the state code instead
of having to iterate over states to work out which one we are in (as in
the switch method) wouldn't have had a chance to shine. Also I expect
much better performance could be obtained by passing the input stream
to the function so it only has to return when it needs to change state.
times to compare the performance of different approaches. One of my
attempts was to have a function for each state, which takes a single
character of input and returns a function pointer to the next state.
This presented an interesting challenge when I tried to code it.
"typedef statefn* (statefn)(int);" is the closest I've got, but of
course you can't refer to the new type within the typedef itself.
I ended up just returning void* and noted this implementation was
terrible[1] compared to the switch and goto solutions, but it's nagging
me that I didn't work out how to define the function properly.
So... is it possible?
(I found a C++ solution at http://www.gotw.ca/gotw/057.htm but nothing
in straight C)
[1] Mind you, my state machine only had 3 states, so the advantage of
the function method has of jumping straight to the state code instead
of having to iterate over states to work out which one we are in (as in
the switch method) wouldn't have had a chance to shine. Also I expect
much better performance could be obtained by passing the input stream
to the function so it only has to return when it needs to change state.