3 ms·
Function pointers as state machines has been a favorite trick of mine for very embedded C stuff. Each function sets the next state function. I actually prefer t
by travisgriggs 4y ago
Function pointers as state machines has been a favorite trick of mine for very embedded C stuff. Each function sets the next state function. I actually prefer this in some cases over a switch machine. I find that big switches don’t scale/self document well.
- saghm 4y agoI'm not super familiar with it, but I seem to remember using the `ucontext` library in my college OS class in a way pretty similar to this. If I recall correctly (and was using it correctly at the time, which is itself potentially an unlikely assumption), it entailed instantiating a struct that would be available as memory to each "state", and then doing basically what you describe with function pointers for state transitions. I remember being vaguely aware that I was essentially creating a directed graph that would be used to determine what to run next, but looking back, I don't think I made the final logical step from there to realizing that this was just an implementation of state machines (which I knew about from my more theory-oriented classes); at the time, I remember thinking that it was a rather cumbersome way to specify what code to run next instead of just writing out everything I wanted in order. I hope my TAs were as amused reading what must have been a giant heap of spaghetti code as I am thinking about it now, but I probably wouldn't be amused actually having it in front of me and having to read it along side a few dozen other project submissions that were written similarly.
- arinlen 4y ago> Function pointers as state machines has been a favorite trick of mine for very embedded C stuff. Each function sets the next state function. This is the basis of OO's State pattern. https://en.wikipedia.org/wiki/State_pattern https://en.wikipedia.org/wiki/State_pattern