tags:

views:

1885

answers:

16

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 breaks (although it's still possible for an unprincipled hacker to simulate continue with an early goto).

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 ifs, 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.

+3  A: 

Here is an example of a good goto:

// No Code
FlySwat
"NO Goto for you!"
Mitch Wheat
er, no gotos? (unsuccessful attempt at funny :d )
moogs
+9  A: 

I have nothing against gotos in general, but I can think of several reasons why you wouldn't want to use them for a loop like you mentioned:

  • It does not limit scope hence any temp variables you use inside won't be freed until later.
  • It does not limit scope hence it could lead to bugs.
  • It does not limit scope hence you cannot re-use the same variable names later in future code in the same scope.
  • It does not limit scope hence you have the chance of skipping over a variable declaration.
  • People are not accustomed to it and it will make your code harder to read.
  • Nested loops of this type can lead to spaghetti code, normals loops will not lead to spaghetti code.
Brian R. Bondy
is inf_loop: {/* loop body */} goto inf_loop; better? :)
quinmars
for the first 4 points yes
Brian R. Bondy
Points 1-4 are dubious *for this example* even without the braces. 1 It's an infinite loop. 2 Too vague to address. 3 Trying to hide a variable of the same name in an enclosing scope is poor practice. 4. A backward goto can't skip a declaration.
fizzer
1-4 as with all infinite loops, you usually have some kind of break condition in the middle. So they are applicable. Re a bakward goto can't skip a declaration... not all gotos are backwards...
Brian R. Bondy
+16  A: 

Here's my non-silly example, (from Stevens APITUE) for Unix system calls which may be interrupted by a signal.

restart:
    if (system_call() == -1) {
        if (errno == EINTR) goto restart;

        // handle real errors
    }

The alternative is a degenerate loop. This version reads like English "if the system call was interrupted by a signal, restart it".

fizzer
this way is used for example linux scheduler have a goto like this but i would say there are very few cases where backwards goto's are acceptable and in general should be avoided.
Ilya
`while(1){if(system_call() == -1){if(errno == EINTR)continue;//handle real errors}}`
Amarghosh
@Amarghosh, `continue` is just a `goto` in a mask.
jball
@jball and is more safe/usable (without leading to spaghetti code) than `goto`
Amarghosh
@Amarghosh - debatably...
jball
@jball ...hmm.. for the sake of argument, yeah; you can make good readable code with goto and spaghetti code with continue.. Ultimately it depends on the person who writes the code. The point is it is easy to get lost with goto than with continue. And newbies normally use the first hammer they get for every problems.
Amarghosh
@Amarghosh. Your 'improved' code isn't even equivalent to the original - it loops forever in the success case.
fizzer
@fizzer oopsie.. it's gonna need two `else break`s (one for each ifs) to make it equivalent.. what can I say... `goto` or not, your code is only as good as you :(
Amarghosh
+8  A: 

If Duff's device doesn't need a goto, then neither should you! ;)

void dsend(int count) {
    int n;
    if (!count) return;
    n = (count + 7) / 8;
    switch (count % 8) {
      case 0: do { puts("case 0");
      case 7:      puts("case 7");
      case 6:      puts("case 6");
      case 5:      puts("case 5");
      case 4:      puts("case 4");
      case 3:      puts("case 3");
      case 2:      puts("case 2");
      case 1:      puts("case 1");
                 } while (--n > 0);
    }
}

code above from Wikipedia entry.

Mitch Wheat
Oh you heartless down voter!
Mitch Wheat
Cmon guys, if you're going to downvote, a short comment as to why would be great. :)
Mitch Wheat
This is an example of a logical fallacy also known as the "appeal to authority". Check it out on Wikipedia.
Marcus Griep
humor is often unappreciated here...
Steven A. Lowe
I wouldn't hire a humourless programmer.
Mitch Wheat
does duff's device make beer?
Steven A. Lowe
this one can make 8 at a time ;-)
Jasper Bekkers
Don't put this device in your code though -- on modern machines it's usually slower than memcpy()
Billy ONeal
why a question that so is old gets downvotes (got one today) I can't understand.
Mitch Wheat
+27  A: 

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 succeed
    return;

cleanupB:
    undoB();
cleanupA:
    undoA();
exit:
    return;
}
Greg Rogers
I *knew* I shoulda taken that "speed typing" course in high school! Good answer.
Adam Liss
What's wrong with this? (apart from the fact that comments don't understand newlines) void foo() { if (doA()) { if (doB()) { if (doC()) { /* everything succeeded */ return; } undoB(); } undoA(); } return; }
Artelius
The extra blocks cause unnecessary indentation that's hard to read. It also doesn't work if one of the conditions is inside a loop.
Adam Rosenfield
You can see a lot of this kind of code in most low level Unix things (like the linux kernel, for example).In C, that's the best idiom for error recovering IMHO.
David Cournapeau
As cournape mentioned, the Linux kernel uses this style *all the time*.
CesarB
Not only linux kernel take a look in Windows driver samples from microsoft and you will find same pattern. In general this is a C way to handle exceptions and very useful one :). I usually prefer only 1 label and in few cases 2. 3 can be avoided in 99% of cases.
Ilya
I've got in trouble at work so many times for using this 'pattern', but I still think it can be the clearest approach to some situations...
Tim Ring
I've also got in trouble for using multiple returns (also usefull in some situations to prevent endless indent levels and indecipherable tortuous code paths).
Tim Ring
+4  A: 

One good place to use a goto is in a procedure that can abort at several points, each of which requires various levels of cleanup. Gotophobes can always replace the gotos with structured code and a series of tests, but I think this is more straightforward because it eliminates excessive indentation:

if (!openDataFile())
  goto quit;

if (!getDataFromFile())
  goto closeFileAndQuit;

if (!allocateSomeResources)
  goto freeResourcesAndQuit;

// Do more work here....

freeResourcesAndQuit:
   // free resources
closeFileAndQuit:
   // close file
quit:
   // quit!
Adam Liss
I would replace this with a set of functions: `freeResourcesCloseFileQuit`, `closeFileQuit`, and `quit`.
RCIX
If you created these 3 extra functions, you'd need to pass pointers/handles to the resources and files to be freed/closed. You'd probably make freeResourcesCloseFileQuit() call closeFileQuit(), which in turn would call quit(). Now you have 4 tightly coupled functions to maintain, and 3 of them will probably be called at most once: from the single function above. If you insist on avoiding goto, IMO, nested if() blocks have less overhead and are easier to read and maintain. What do you gain with 3 extra functions?
Adam Liss
A: 

My gripe about this is that you lose block scoping; any local variables declared between the gotos remains in force if the loop is ever broken out of. (Maybe you're assuming the loop runs forever; I don't think that's what the original question writer was asking, though.)

The problem of scoping is more of an issue with C++, as some objects may be depending on their dtor being called at appropriate times.

For me, the best reason to use goto is during a multi-step initialization process where the it's vital that all inits are backed out of if one fails, a la:

if(!foo_init())
  goto bye;

if(!bar_init())
  goto foo_bye;

if(!xyzzy_init())
  goto bar_bye;

return TRUE;

bar_bye:
 bar_terminate();

foo_bye:
  foo_terminate();

bye:
  return FALSE;
Jim Nelson
+1  A: 

@Greg:

Why not do your example like this:

void foo()
{
    if (doA())
    {    
        if (doB())
        {
          if (!doC())
          {
             UndoA();
             UndoB();
          }
        }
        else
        {
          UndoA();
        }
    }
    return;
}
FlySwat
It adds unnecessary levels of indentation, which can get really hairy if you have a large number of possible failure modes.
Adam Rosenfield
I'd take indentations over goto anyday.
FlySwat
Also, it's far more lines of code, has a redundant function call in one of the cases and is far harder to add a doD to correctly.
Patrick
I agree with Patrick - I've seen this idiom used with several conditions that nested to a depth of about 8 levels. Very nasty. And very error prone, especially when trying to add something new to the mix.
Michael Burr
This code is just scream "I will have a bug in few next weeks" somebody will forget to undo something. You need all your undo in same place. It's just like "finally" in native OO languages.
Ilya
I don't like the copy-and-pasted repetition of "UndoA()". C'n'P code is approximately as bad as goto, and for me in this case it loses because it's more verbose. Also the fact that B is done after A, and also undone after A, makes my teeth curl, but that's not part of the pattern here.
Steve Jessop
You could rewrite this with less nesting by doing if(!doA()) { return; }if(!doB()) { UndoA(); return; }and so on. You'd still have the duplicate function calls, but at least the code would be readable.
Tommy
Why couldn't you use a case statement here?
Austin
RAII >> goto >> this crap.
Alexandre C.
+7  A: 

@fizzer.myopenid.com: your posted code snippet is equivalent to the following:

    while (system_call() == -1)
    {
        if (errno != EINTR)
        {
            // handle real errors

            break;
        }
    }

I definitely prefer this form.

Mitch Wheat
OK, I know the break statement is just a more acceptable form of goto..
Mitch Wheat
To my eyes, it's confusing. It's a loop which you don't expect to enter in the normal execution path, so the logic seems backwards. Matter of opinion, though.
fizzer
Backwards? It starts, it continues, it falls through. I think this form more obviously states its intentions.
Mitch Wheat
I'd agree with fizzer here that the goto provides a clearer expectation as to the condition's value.
Marcus Griep
OK we will have to disagree on that one.
Mitch Wheat
+1 because the while version is both clearer and avoid the use of goto, which have some limitation of passing through object construction.
paercebal
In which way is this snippet easier to read than fizzer's.
erikkallen
+6  A: 

Very common.

do_stuff(thingy) {
    lock(thingy);

    foo;
    if (foo failed) {
        status = -EFOO;
        goto OUT;
    }

    bar;
    if (bar failed) {
        status = -EBAR;
        goto OUT;
    }

    do_stuff_to(thingy);

OUT:
    unlock(thingy);
    return status;
}

The only case I ever use goto is for jumping forwards, usually out of blocks, and never into blocks. This avoids abuse of do{}while(0) and other constructs which increase nesting, while still maintaining readable, structured code.

ephemient
I think this is the typcial C way of error handling. I can not see it replaced nicely, better readable any other way Regards
Friedrich
+26  A: 

The classic need for GOTO in C is as follows

for ...
  for ...
    if(breakout_condition) 
      goto final;

final:

There is no straightforward way to break out of nested loops without a goto.

Paul Nathan
To add to this: the way to do it without a goto would be to set a boolean flag, and test that flag each iteration of each outer loop. This produces less readable code; it's also marginally less efficient, but that's only relevant in a rare number of cases (e.g. kernel code).
Adam Rosenfield
Most often when this need comes up I can use a return instead. But you need to be writing small functions for it to work out that way.
Darius Bacon
I definitely agree with Darius - refactor it to a function and return instead!
metao
Johnathan - break only breaks out of the closest loop.Darius - sure. But this is the classic Goto In C example.
Paul Nathan
@metao: Bjarne Stroustrup disagree. On his C++ Programming Language book, this is exactly the example given of a "good use" of goto.
paercebal
@Adam Rosenfield: The *whole problem* with goto, highlighted by Dijkstra, is that structured programming offers more comprehensible constructs. Making code harder to read in order to avoid goto proves that the author failed to understand that essay...
Steve Jessop
Why would you have final in that code? Break it out into a function.
Austin
+3  A: 

Even though I've grown to hate this pattern over time, it's in-grained into COM programming.

#define IfFailGo(x) {hr = (x); if (FAILED(hr)) goto Error}
...
HRESULT SomeMethod(IFoo* pFoo) {
  HRESULT hr = S_OK;
  IfFailGo( pFoo->PerformAction() );
  IfFailGo( pFoo->SomeOtherAction() );
Error:
  return hr;
}
JaredPar
A: 

I don't use goto's myself, however I did work with a person once that would use them in specific cases. If I remember correctly, his rationale was around performance issues - he also had specific rules for how. Always in the same function, and the label was always BELOW the goto statement.

Additional data: note that you cannot use goto to go outside the function, and that in C++, it is forbidden to bypass an object construction through a goto
paercebal
+6  A: 

Knuth has written a paper "Structured programming with GOTO statements", you can get it e.g. from here. You'll find many examples there.

zvrba
This paper looks deep. I will read it though. Thanks
fizzer
That paper is *so* out of date, it's not even funny. Knuth's assumptions there simply don't hold any longer.
Konrad Rudolph
Which assumptions? His examples are as real today for a procedural language as C (he gives them in some pseudo-code) as they were at that time.
zvrba
A: 

In many situations you can elegantly replace gotos with a while(true) loop and break statements:

while(true) {
  if (!doA()) {
    break;
  }
  if (!doB()) {
    cleanUpA();
    break;
  }
  if (!doC()) {
    cleanUpA();
    cleanUpB();
    break;
  }
  break;
}
kgiannakakis
That's less elegant than the goto.
Steve Jessop
But more elegant than the nested if:s...
Andreas Magnusson
The duplication of cleanUpA() is inelegant
camh
This is elegant?
EvilTeach
Not only is it less elegant it uses goto (break)
frankc
+1  A: 

I've seen goto used correctly but the situations are normaly ugly. It is only when the use of goto itself is so much less worse than the original. @Johnathon Holland the poblem is you're version is less clear. people seem to be scared of local variables:

void foo()
{
    bool doAsuccess = doA();
    bool doBsuccess = doAsuccess && (doB() == true);
    bool doCsuccess = doBsuccess && (doC() == true);

    if (doCsuccess ==false)
    {
        if (doBsuccess == true)
            undoB();
        if (doAsuccess == true)
            undoA();
    }
}

And I prefer loops like this but some people prefer while(true).

for (;;)
{
    //code goes here
}
Charles Beattie