In this thread, we look at examples of good uses of goto
in C or C++. It's inspired by an answer which people voted up because they thought I was joking.
Summary (label changed from original to make intent even clearer):
infinite_loop:
// code goes here
goto infinite_loop;
Why it's better than the alternatives:
- It's specific.
goto
is the language construct which causes an unconditional branch. Alternatives depend on using structures supporting conditional branches, with a degenerate always-true condition. - The label documents the intent without extra comments.
- The reader doesn't have to scan the
intervening code for early
break
s (although it's still possible for an unprincipled hacker to simulatecontinue
with an earlygoto
).
Rules:
- Pretend that the gotophobes didn't win. It's understood that the above can't be used in real code because it goes against established idiom.
- Assume that we have all heard of 'Goto considered harmful' and know that goto can be used to write spaghetti code.
- If you disagree with an example, criticize it on technical merit alone ('Because people don't like goto' is not a technical reason).
Let's see if we can talk about this like grown ups.
Edit
This question seems finished now. It generated some high quality answers. Thanks to everyone,
especially those who took my little loop example seriously. Most skeptics were concerned
by the lack of block scope. As @quinmars pointed out in a comment, you can always put braces around the
loop body. I note in passing that for(;;)
and while(true)
don't give you the braces
for free either (and omitting them can cause vexing bugs). Anyway, I won't waste any more
of your brain power on this trifle - I can live with the harmless and idiomatic for(;;)
and while(true)
(just as well if I want to keep my job).
Considering the other responses, I see that many people view goto
as something you always
have to rewrite in another way. Of course you can avoid a goto
by introducing a loop,
an extra flag, a stack of nested if
s, or whatever, but why not consider whether goto
is
perhaps the best tool for the job? Put another way, how much ugliness are people prepared to endure to avoid using a built-in language feature for its intended purpose? My take is that
even adding a flag is too high a price to pay. I like my variables to represent things in
the problem or solution domains. 'Solely to avoid a goto
' doesn't cut it.
I'll accept the first answer which gave the C pattern for branching to a cleanup block. IMO, this makes the strongest case for a goto
of all the posted answers, certainly
if you measure it by the contortions a hater has to go through to avoid it.
for (;;)
) has no surprising entry points. – Atcliffedo{}while(0);
like in this constructiondo{ if( 1 > 0 ){ break;} } while(0);
– Destine