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

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

问题描述

这问题其实是一个结果<一个href=\"http://www.reddit.com/r/programming/comments/8cx8m/error_handling_in_c_you_are_going_to_fail_in_a/\"相对=nofollow>在programming.reddit.com有趣的讨论前一阵子。它基本上可以归结为以下code:

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;
}

转到的用法这里似乎是最好的一段路要走,导致所有的可能性,最清洁,最高效的code,或者至少使其对我来说。在引用史蒂夫·麦康奈尔的 code完成的:

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是在例行有用的
  分配资源,执行
  对这些资源的操作,并
  然后将释放的资源。随着
  跳转,你可以在一节清理
  的code。其中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.

你觉得呢?这是情况下转到的有效利用?你会preFER等方法,从而产生更加错综复杂和/或低效率code,但要避免转到

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,我发现你在问题的例子给了错误处理的成语更容易阅读和比任何至今在答案中给出的替代品的了解。而转到是一般一个坏主意,在一个简单而统一的方式进行时,它可以用于错误处理很有用。在这种情况下,即使它是一个转到,它被用于明确和或多或少的结构化的方式。

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.

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

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