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 goto
s 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 goto
s seems awkward. On the other hand, we've been raised to condemn the use of goto
s 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
.
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."
You can't.
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.
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.
Your usage of goto
is ok. It doesn't break the 2 good ways to use goto.
goto
s MUST go down (a few lines) in the sourcegoto labels
MUST contain the goto
statementsIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With