问题描述
的转到
语句已在几个SO讨论连篇累牍检查(见的和的),我当然不希望重振那些激烈的辩论。
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.
相反,我想集中精力的S 转到
单一的用例,并讨论其价值和可能的替代方案。
Instead, I'd like to concentrate on a single use case of goto
s and discuss its value and possible alternatives.
考虑以下code片段,这是常见的(至少我自己)的FSM:
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.
我的问题:我的code例如考虑好作风?
如果不是,是否有可行的替代品?
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
.
推荐答案
您转到
的使用就可以了。它不破2好的方式使用goto语句。
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 source- The innermost block of
goto labels
MUST contain thegoto
statements
这篇关于GOTO认为无害的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!