why do people hate gotos again? my prof said it decreases readability but.....
Top:
........
goto Top;
GEE WONDER WHAT THE FUCK I DO IM SO FUCKING STUMPED AS TO WHAT THE PROGRAM WILL DO HERE
I mean really why are they so bad?
Name:
Anonymous2010-10-27 14:02
I usually only use goto (or its equivalents in other languages) for these purposes:
1) When breaking out of nested loops in C-like languages which don't provide multi-level break/exit statements/operators (some fancier languages do provide much better solutions for this, Common Lisp comes to mind almost immediately). Also used for cleanup/error handling in C as well when it makes sense to do so. Usually you should only use goto (or equivalents) when you can't use a more specific statement that the language provides to solve the problem. Of course, you can in many cases avoid goto by adding useless conditionals (which could slow down the code), but since that new code is not semantically equivalent to the one with the most straightforward goto, it's usually a fine use scenario.
2) For performance reasons in certain very tight loops. It can be a great time saver if the only alternative is to add a conditional which would have to get executed a lot more often and thus diminishing the overall performance, possibly by quite a lot. (One notable example that happened to me was some crypto bruteforce code where every memory access and compare counts. It got a 3 times speedup, leading to results being found in 1.5 minutes as opposed to 4-5min).
3) In generated code. There's absolutely no shame in using goto's here as all compilers do translate a lot of control-flow constructs to goto's (or jumps if you wish). I've used it quite a few times in CL macros. The gotos themselves don't obscure the intent of the code as they're not really visible (they're internal details that the compiler will have to handle, and the labels are gensyms anyway). Of course, TCO+lambda is more powerful than goto, and throw/catch, block/return-from, ... are also more powerful than it, but they can also be overkill (stack unwinding), however I fear discussing this further won't really help OP much as this is far from the usual C territory (albeit, you can achieve a lot of this in C, some as is, other with compiler hacking, but if you do that, all bets are off anyway).
4) Another legitimate case are state machines, a lot of times they can be described most naturally by the use of goto, and their translation is most natural. One could probably say the same for translating code written in other languages or obscure assemblies (both automatic translation or manual). For example, you could translate some of Knuth's olde recipes. Of course, most of Knuth's algorithms can be written in goto form if you translate them directly, but then you can rewrite them in a way that makes more sense and is properly structured code, however having the option to do it either way is useful.