5 ms·
I'm not surprised to see them in a compiler. When you're parsing and want to treat it as a big state machine, gotos are your best friend.
by daeken 13y ago
I'm not surprised to see them in a compiler. When you're parsing and want to treat it as a big state machine, gotos are your best friend.
- bakul 13y agoExcept in languages with tail recursion such as Scheme! A state ends with a call to the next state instead of a goto next state.
- clarry 13y agoEncoding state implicitly in control flow tends to give you nicer and more natural code. A big state machine implemented with gotos can be tough to read if it's also a parser (which may need to build a tree, recurse, etc.). A small hand-rolled lexer might be reasonable to implement with goto. Although I would prefer to enumerate the states and use a switch. If you're writing a recursive descent parser for C while keeping minimal lookahead, I can think of a place or two where goto might really help. One is to deal with casts, compound literals and subexpressions. They all begin with a left-parenthesis, so you can't tell what you're dealing with until a bit further. Since these all appear in the parsing of simple expressions (identifiers, constants, unary operators), the code can go in one function and you can jump to the right place with goto as soon as you know what you are dealing with. I did not look in the Go code but C programmers mostly use goto for error paths.