Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is GOTO considered harmless when jumping to cleanup at the end of function?

Tags:

The goto statement has been examined at great length in several SO discussions (see this and that), and I certainly don't want to revive those heated debates.

Instead, I'd like to concentrate on a single use case of gotos and discuss its value and possible alternatives.

Consider the following code snippet, which is common in (at least my own) FSMs:

while (state = next_state()) {         switch (state) {                 case foo:                         /* handle foo, and finally: */                         if (error) goto cleanup;                         break;                 case bar:                         /* handle bar, and finally: */                         if (error) goto cleanup;                         break;                 /* ...other cases... */         } }  return ok;  cleanup: /* do some cleanup, i.e. free() local heap requests, adjust global state, and then: */ return error; 

Swapping out the cleanup stuff in a separate function just in order to save the gotos seems awkward. On the other hand, we've been raised to condemn the use of gotos wherever possible.

My question: is my code example considered good style?
If not, are there feasible alternatives available?

Please adhere to the specific usage of goto described above. I don't want to delve into yet another discussion about the general use of goto.

like image 969
Philip Avatar asked Apr 18 '11 11:04

Philip


People also ask

Why should goto be avoided?

In fact, IDL's own documentation advises against it. Actually, it doesn't advise against it; it outright states that using it is bad programming: "The GOTO statement is generally considered to be a poor programming practice that leads to unwieldy programs. Its use should be avoided."

Can goto be used to jump across functions?

You can't.

What does the goto function do?

GoTo (goto, GOTO, GO TO or other case combinations, depending on the programming language) is a statement found in many computer programming languages. It performs a one-way transfer of control to another line of code; in contrast a function call normally returns control.

What is goto jump statement?

The goto statement is a jump statement which is sometimes also referred to as unconditional jump statement. The goto statement can be used to jump from anywhere to anywhere within a function.


1 Answers

Your usage of goto is ok. It doesn't break the 2 good ways to use goto.

  1. gotos MUST go down (a few lines) in the source
  2. The innermost block of goto labels MUST contain the goto statements
like image 157
pmg Avatar answered Nov 11 '22 08:11

pmg