Goto Considered (Mostly) Harmful

Rich Burridge has written about coding style. I’m not an expert on style but I will comment that the motivation for his comments, the goto statement, does not preclude good style. Gratuitous use of goto is obviously bad, but here is an example (used widely in the Linux kernel) of where it can do some good. In C goto can be used as a primitive form of exception handling.

void foo (int bar)
{
    char *a, *b;

    a = allocate_something (bar);
    if (error) return;

    b = allocate_something_else ();
    if (error) goto deallocate_a;

    do_something (a,b);

    free (b);
deallocate_a:
    free (a);
}

vs.

void foo (int bar)
{
    char *a, *b;

    a = allocate_something (bar);

    if (!error) {
        b = allocate_something_else ();

        if (!error) {
             do_something (a,b);
	     free (b);
        }
        free (a);
    }
}

You can see that with incresing numbers of allocations the second case will quickly get out of hand. By sticking to the “correct” control structures we have hidden the basic structure of the function, a plain sequence of instructions, behind all the branches necessary to handle errors. In the first case we have made the visual flow of the code the same as the normal flow of the code. The compiler produces the same object code in either case.

In general I think Dijkstra is right about gotos, but there is a space on this planet for even the spiny poisonous creatures.


Posted

in

by

Tags: