[c++] Examples of good gotos in C or C++

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.

This question is related to c++ c goto

The answer is


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;

@Greg:

Why not do your example like this:

void foo()
{
    if (doA())
    {    
        if (doB())
        {
          if (!doC())
          {
             UndoA();
             UndoB();
          }
        }
        else
        {
          UndoA();
        }
    }
    return;
}

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.


@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.


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;
}

Here is an example of a good goto:

// No Code

@Greg:

Why not do your example like this:

void foo()
{
    if (doA())
    {    
        if (doB())
        {
          if (!doC())
          {
             UndoA();
             UndoB();
          }
        }
        else
        {
          UndoA();
        }
    }
    return;
}

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.


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.


@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.


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.


Here is an example of a good goto:

// No Code

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!

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


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;
}

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.


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!

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();
    bool doCsuccess = doBsuccess && doC();

    if (!doCsuccess)
    {
        if (doBsuccess)
            undoB();
        if (doAsuccess)
            undoA();
    }
}

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

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

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.

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.


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.


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.

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();
    bool doCsuccess = doBsuccess && doC();

    if (!doCsuccess)
    {
        if (doBsuccess)
            undoB();
        if (doAsuccess)
            undoA();
    }
}

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

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

#include <stdio.h>
#include <string.h>

int main()
{
    char name[64];
    char url[80]; /*The final url name with http://www..com*/
    char *pName;
    int x;

    pName = name;

    INPUT:
    printf("\nWrite the name of a web page (Without www, http, .com) ");
    gets(name);

    for(x=0;x<=(strlen(name));x++)
        if(*(pName+0) == '\0' || *(pName+x) == ' ')
        {
            printf("Name blank or with spaces!");
            getch();
            system("cls");
            goto INPUT;
        }

    strcpy(url,"http://www.");
    strcat(url,name);
    strcat(url,".com");

    printf("%s",url);
    return(0);
}

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();
    bool doCsuccess = doBsuccess && doC();

    if (!doCsuccess)
    {
        if (doBsuccess)
            undoB();
        if (doAsuccess)
            undoA();
    }
}

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

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

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.


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


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();
    bool doCsuccess = doBsuccess && doC();

    if (!doCsuccess)
    {
        if (doBsuccess)
            undoB();
        if (doAsuccess)
            undoA();
    }
}

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

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

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!

@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.


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.


@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.


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


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;
}

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".


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.


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".


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;

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.

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;

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.


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.


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.

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".


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;

@Greg:

Why not do your example like this:

void foo()
{
    if (doA())
    {    
        if (doB())
        {
          if (!doC())
          {
             UndoA();
             UndoB();
          }
        }
        else
        {
          UndoA();
        }
    }
    return;
}

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.


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.


@Greg:

Why not do your example like this:

void foo()
{
    if (doA())
    {    
        if (doB())
        {
          if (!doC())
          {
             UndoA();
             UndoB();
          }
        }
        else
        {
          UndoA();
        }
    }
    return;
}

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.


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!

#include <stdio.h>
#include <string.h>

int main()
{
    char name[64];
    char url[80]; /*The final url name with http://www..com*/
    char *pName;
    int x;

    pName = name;

    INPUT:
    printf("\nWrite the name of a web page (Without www, http, .com) ");
    gets(name);

    for(x=0;x<=(strlen(name));x++)
        if(*(pName+0) == '\0' || *(pName+x) == ' ')
        {
            printf("Name blank or with spaces!");
            getch();
            system("cls");
            goto INPUT;
        }

    strcpy(url,"http://www.");
    strcat(url,name);
    strcat(url,".com");

    printf("%s",url);
    return(0);
}

Here is an example of a good goto:

// No Code

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


Here is an example of a good goto:

// No Code

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.


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;
}

Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to c

conflicting types for 'outchar' Can't compile C program on a Mac after upgrade to Mojave Program to find largest and second largest number in array Prime numbers between 1 to 100 in C Programming Language In c, in bool, true == 1 and false == 0? How I can print to stderr in C? Visual Studio Code includePath "error: assignment to expression with array type error" when I assign a struct field (C) Compiling an application for use in highly radioactive environments How can you print multiple variables inside a string using printf?

Examples related to goto

How to use goto statement correctly The equivalent of a GOTO in python How can I use goto in Javascript? Is there a "goto" statement in bash? Is there a goto statement in Java? Alternative to a goto statement in Java VB.NET Switch Statement GoTo Case Is there a label/goto in Python? Examples of good gotos in C or C++