top of page
Search

goto hell (Are Gotos That Bad?)

  • Writer: Kiranbir Sodhia
    Kiranbir Sodhia
  • May 18, 2013
  • 2 min read

Never use a goto. Sound like someone you know? It’s something we all heard our high school computer programming teacher or friend say. If you were a nerd and loser in high school like me, they were probably the same person.

There’s a lot of debate about whether gotos or multiple return points are “really” bad. Some of the reasons they are generally discouraged is because they can lead to producing spaghetti code and the flow of a function make no longer be top-to-bottom. However, there are many places where they make sense. For example, jumping to a common cleanup section before your function returns.

You’ll often hear people rant about how gotos are bad, but end up using a similar jump pattern for the same functionality just to avoid using the keyword goto.

Below is a snippet of leaving a function at any point in the code.

int function ( void )
{
    // do some work...
    if ( x )  
    {
        // free resources
        return 1;
    }
    // do more work...
    if ( z )
    {
        // free resources
        return 2;
    }
    // final work...
    // free resources
    return 3;
}

There isn’t anything wrong, however, it might be dangerous if there is allocations that aren’t freed before each return statement. This is why you will often see a goto to a cleanup section.

int function ( void )
{
    // do some work...
    if ( x )
        ret = 1;
        goto cleanup;
    // do more work...
    if ( z )
        ret = 2;
        goto cleanup:
    // final work...
    ret = 3

cleanup:
    // free any of the resources I allocated if they exist
    return ret;
}

Here is an example of where someone clearly used a goto in their code, just not in their wording:

int function( void )
{
    do
    {
        // do some stuff
        if (x)
            break;
        // do more stuff
        if ( y )
            break;
        // do more stuff
        if ( z )
            break;
        // do more stuff
    } while (0)
    // free resources
    return something;
}

There’s a great rant on this involving Linus Torvalds (http://kerneltrap.org/node/553/2131). This is my favorite part from the discussion:

From: Scott Robert Ladd
Subject: RE: any chance of 2.6.0-test*?
Date:   Sun, 12 Jan 2003 19:03:10 -0500

<omitted>
A "goto" is not, in and of itself, dangerous -- it is a language feature,
one that directly translates to the jump instructions implemented in machine
code. Like pointers, operator overloading, and a host of other "perceived"
evils in programming, "goto" is widely hated by those who've been bitten by
poor programming. Bad code is the product of bad programmers; in my
experience, a poor programmer will write a poor program, regardless of the
availability of "goto."
 
 
 

Recent Posts

See All

Comments


bottom of page