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:
goto
is the
language construct which causes an
unconditional branch. Alternatives
depend on using structures
supporting conditional branches,
with a degenerate always-true
condition.break
s
(although it's still possible for an
unprincipled hacker to simulate
continue
with an early goto
).Rules:
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.
Heres one trick I've heard of people using. I've never seen it in the wild though. And it only applies to C because C++ has RAII to do this more idiomatically.
void foo()
{
if (!doA())
goto exit;
if (!doB())
goto cleanupA;
if (!doC())
goto cleanupB;
/* everything has succeeded */
return;
cleanupB:
undoB();
cleanupA:
undoA();
exit:
return;
}