3 ms·
Gotos are a natural choice for state machines, we basically emulate goto when we use while+switch or while+function pointer. The "goto considered harmful" paper
by klodolph 9y ago
Gotos are a natural choice for state machines, we basically emulate goto when we use while+switch or while+function pointer. The "goto considered harmful" paper is about structured programming, saying that you should use structured programming instead of goto, but it doesn't apply here because goto is the right structure to begin with.
I suggest reading the actual "goto" paper sometime… it's a classic.
- marcosdumay 9y agoI just want to add that the "goto" criticized on that paper does not exist anymore in any modern language (that includes C). Goto has been nerfed into something that can not destroy structured programming. But I do think the while+switch representation is superior.
- klodolph 9y agoThe while+switch, to me, looks like goto with extra typing. state = START; break; Translates directly to: goto start; Except while+switch is nicer if you have transition tables. YMMV
- marcosdumay 9y agoYes, but it forces you to keep your state as data, and makes it much more clear how the data relates to the code. But it does make for the same exact behavior.
- klodolph 9y agoThe state is data either way... either an explicit variable or the program counter. With goto, the compiler is more likely to be able to see across state change boundaries (e.g. phi() will work correctly without doing anything fancy). So you can, e.g., have the compiler help you out by giving you warnings for uninitialized variables, when the variables are initialized in one state and used in another.
- zokier 9y ago> I just want to add that the "goto" criticized on that paper does not exist anymore in any modern language (that includes C). It might not be called goto, but isn't setjmp/longjmp essentially the same?
- klodolph 9y agoNo... you can only longjmp if the jmp_buf corresponds to a setjmp created within a function call which hasn't returned yet and in the same thread. I would call this a primitive form of structured programming with some serious limitations--it's kind of like throwing an exception, but more primitive, and it's kind of like the Common Lisp block/return-from, except less convenient, and it's kind of like call/cc but with a bunch of limitations added. You can do some dangerous things with longjmp to implement coroutines, but it's horribly non-portable.
- Sacho 9y agoPattern matching is so much sexier than switch statements. Writing state machines is one of the moments when the 1d top-down method of programming really hurts. I feel like I can easily understand an FSM drawing, but splay it out in code and it's difficult to track.