GOTO认为无害 [英] GOTO considered harmless

查看:144
本文介绍了GOTO认为无害的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

转到语句已在几个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 gotos 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 gotos seems awkward. On the other hand, we've been raised to condemn the use of gotos 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.


  1. 转到取值必须在源往下走(几行)

  2. 转到标签的最里面块必须包含转到语句

  1. gotos MUST go down (a few lines) in the source
  2. The innermost block of goto labels MUST contain the goto statements

这篇关于GOTO认为无害的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆