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

查看:132
本文介绍了在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 这里似乎是最好的方法,导致所有可能性的最干净,最有效的代码,或至少在我看来。引用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,您可以在
的代码中清理。 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设备驱动程序书,本节

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