Debashish Chakravarty <> wrote:
> K&R pg.66 describes two situations when using goto makes sense. Has
> anyone here come across situations where using goto provided the most
> elegant solution.
The classic case is breaking out of a nested loop from the inside.
While people who hate goto for some reason despise such things and
prefer having extra if-checks to account such a condition, its slower,
and just makes your code more complicated.
But another interesting case is with state machines. While the
classic implementation of a state matchine is to simply put a switch
statement inside of a while (1) { ... } loop, this has a drawback of
requiring the switch statement to be execute on every state change (on
modern processors this is much slower than direct gotos.) But as an
alternative, one could simply have one switch statement and rather
than breaks at the end of each case block, simply have gotos to the
blocks that represent the state transition. You have to have labels
that are redundant with the case ...: statements, however this
solution is much faster, and doesn't require that you maintain a state
variable (since the state itself would be redundant with the case
clause that was being executed at any one time) for all states (just
entry and exit of the state machine.)
Finally sometimes its best, for performance reasons to start a loop in
the middle of the body of the loop rather than a start. So you have a
goto just before your do {...} while or for() loop to enter in the
middle of it.
These are probably the most interesting marginal cases where using
goto is the best solution in the C language. The problem is that
there are many other uses of goto which are really really bad. So
much so that people have railed against its usage, and will actually
choose not to do so in any situation. They will lose performance
and/or make their code complicated in all of the above cases. So this
*should* make a good case for improving improving the language so that
these operations can be done *without* goto (for example <break n;> to
jump out of n nested blocks, and <continue case ___;> to jump to a
case within the nearest enclosing switch scope.) However, I don't
know if the C standards committee is open to suggestions such as
these.
--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/