C: goto statement considered helpful

Since Dijkstra's paper "Goto statement considered harmful" goto tends not to be used because it is prone to produce spaghetti unreadable code.

But goto is also helpful in some situations, and leads to cleaner code (This article talks about C code basicly)

In C, goto statement allows us to jump to a different part of current function.

Exception mechanism for C

C lacks an exception mechanism. One useful way to recover from an error situation is calling "goto error_label;"
At this point resources for that function are freed and it can end cleanly.

Not only for errors, but as a destructor point for cleansing, even if function ends with success to always free resources used by that function.
goto clean_label;

The usefulness of goto in this situation depends on the resources we have to clean. We are able to jump from some inner nested loops and directly free the unneeded resources.

State machines

When we want to implement a finite state machine goto may become handy.

Each state is associated with a label and goto jumps to that state.

E.g: coding a menu for a GUI could match this situation, or parsing a configuration file.

In this case it avoids excessive loop nesting, but could also be implemented using C switch statement.

NOTE: Error if we create a label and after it a declaration appears

int a;

When compiling an error occurs:
"error: a label can only be part of a statement and a declaration is not a statement"

We can solve this error creating a void statement after the label:
label_example: ;
int a;


Goto statement considered harmful (Dijkstra)

Linus Torvalds' comments about goto in kernel code