在功能结束时跳转至清理程序时,GOTO是否被认为是无害的? [英] Is GOTO considered harmless when jumping to cleanup at the end of function?

查看:74
本文介绍了在功能结束时跳转至清理程序时,GOTO是否被认为是无害的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

相反,我想专注于 goto s的单个用例,然后

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

请考虑以下代码片段,这在(至少是我自己的)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;

为了保存,将清理工作交换到一个单独的函数中goto 似乎很尴尬。另一方面,我们提请我们谴责尽可能使用 goto s。

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?

请遵守 goto的特定用法。我不想深入讨论有关 goto 的一般用法。

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.

推荐答案

使用 goto 没问题。并没有打破使用goto的2种好方法。

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


  1. goto s必须在源代码中向下(几行)

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

  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天全站免登陆