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
.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…