Note that there are some explanatory texts on larger screens.

plurals
  1. POValid use of goto for error management in C?
    text
    copied!<p>This question is actually a result of an <a href="http://www.reddit.com/r/programming/comments/8cx8m/error_handling_in_c_you_are_going_to_fail_in_a/" rel="noreferrer">interesting discussion</a> at programming.reddit.com a while ago. It basically boils down to the following code:</p> <pre><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></pre> <p>The usage of <code>goto</code> 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 <em>Code Complete</em>:</p> <blockquote> <p>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.</p> </blockquote> <p>Another support for this approach comes from the <em>Linux Device Drivers</em> book, in <a href="http://www.xml.com/ldd/chapter/book/ch02.html#buierr" rel="noreferrer">this section</a>.</p> <p>What do you think? Is this case a valid use for <code>goto</code> in C? Would you prefer other methods, which produce more convoluted and/or less efficient code, but avoid <code>goto</code>?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload