It is common knowledge that usages of the goto statement are
potentially dangerous in any structured programming language, as their
abuse can quickly make your code unreadable. This is why this
construction is seldom explained to people learning how to program and
their use is strongly discouraged.
However, there are some situations in which it is very useful and,
despite what some people might say, makes your code more readable. I had
never used gotos before, but have experienced this recently while
writing tmpfs.
One of the situations where a goto is useful is when you need break
from within a set of nested loops. This is the most cited example of
“correct” usage of this statement, but personally, I don’t like it. FWIW
some languages, such as Perl, provide a nice
break statement to do exactly this.
Another scenario where goto is useful is what I’m using it for now: to
control all exit conditions from a function. Instead of placing return
statements all around inside them (after each error check, for example),
I put a goto that jumps to the end of the function; that block is
responsible for checking postconditions, doing any necessary cleanup and
return the correct error code.
Here is an outline of such a function:
int
foo(...)
{
int error;
/* Check function preconditions here using assert(3). */
if (error condition one) {
error = EFOO;
goto out;
}
if (error condition two) {
error = EBAR;
goto out;
}
/* Code executed when there are no errors. */
error = 0;
out:
/* Release unneeded resources here. */
/* Check function postconditions here using assert(3). */
return error;
}
As you can see, if I wanted to avoid using gotos, I’d have to
duplicate a lot of code inside each error condition check. Using this
structure, all exit-related stuff is kept in just one place; specially
postconditions (remember that they must be fulfilled whichever action
the function did). And the function is far more readable (at least to my
eyes).
If you have any other example of nice goto usages, or if you see
another way to do what I described above, please share! ;-)
Subscribe to the Julipedia to stay tuned on posts similar to this one and read more about this blog to see what you may be missing!
(Content also available at: gemini://capsule.jmmv.dev/post/2005/08/using-gotos-in-c.gmi)