在 C 中有效地使用 goto 进行错误管理? [英] Valid use of goto for error management in C?

查看:32
本文介绍了在 C 中有效地使用 goto 进行错误管理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题实际上是 有趣的讨论的结果不久前programming.reddit.com.基本上可以归结为以下代码:

This question is actually a result of an interesting discussion at programming.reddit.com a while ago. It basically boils down to the following code:

int foo(int bar)
{
    int return_value = 0;
    if (!do_something( bar )) {
        goto error_1;
    }
    if (!init_stuff( bar )) {
        goto error_2;
    }
    if (!prepare_stuff( bar )) {
        goto error_3;
    }
    return_value = do_the_thing( bar );
error_3:
    cleanup_3();
error_2:
    cleanup_2();
error_1:
    cleanup_1();
    return return_value;
}

在此处使用 goto 似乎是最好的方法,可以生成所有可能性中最干净、最高效的代码,或者至少在我看来是这样.在 Code Complete 中引用 Steve McConnell:

The usage of goto here appears to be the best way to go, resulting in the cleanest and most efficient code of all possibilities, or at least so it seems to me. Quoting Steve McConnell in Code Complete:

goto 在例程中很有用分配资源,执行对这些资源的操作,以及然后释放资源.用一个转到,您可以在一节中清理的代码.goto 减少了你忘记的可能性释放每个地方的资源您检测到错误.

The goto is useful in a routine that allocates resources, performs operations on those resources, and then deallocates the resources. With a goto, you can clean up in one section of the code. The goto reduces the likelihood of your forgetting to deallocate the resources in each place you detect an error.

对这种方法的另一个支持来自 Linux Device Drivers 一书,位于 本节.

Another support for this approach comes from the Linux Device Drivers book, in this section.

你怎么看?这种情况是否可以在 C 中有效使用 goto ?您是否更喜欢其他方法,这些方法会产生更复杂和/或效率更低的代码,但要避免 goto?

What do you think? Is this case a valid use for goto in C? Would you prefer other methods, which produce more convoluted and/or less efficient code, but avoid goto?

推荐答案

FWIF,我发现您在问题示例中给出的错误处理习语比目前答案中给出的任何替代方案都更具可读性和更容易理解.虽然 goto 通常是一个坏主意,但如果以简单和统一的方式完成,它对于错误处理很有用.在这种情况下,即使它是一个 goto,它也以明确定义和或多或少结构化的方式使用.

FWIF, I find the error handling idiom you gave in the question's example to be more readable and easier to understand than any of the alternatives given in the answers so far. While goto is a bad idea in general, it can be useful for error handling when done in a simple and uniform manner. In this situation, even though it's a goto, it's being used in well-defined and more or less structured manner.

这篇关于在 C 中有效地使用 goto 进行错误管理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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