4 ms·
You would put the cleanup code in a separate function, and call it. I don't think there's anything wrong with using goto in such a case, though, if it makes th
by IsaacSchlueter 14y ago
You would put the cleanup code in a separate function, and call it.
I don't think there's anything wrong with using goto in such a case, though, if it makes the code more understandable.
- humbledrone 14y agoJust putting the cleanup code in a separate function doesn't solve the problem. In C, goto can be used as a kind of fall-through mechanism to clean up all of the resources a function has acquired (but no more!), in the opposite order that they were acquired. There really is no other way to accomplish this without horrible if/else nesting, which for complex functions would be pretty ridiculous. [1] http://eli.thegreenplace.net/2009/04/27/using-goto-for-error-handling-in-c/ http://eli.thegreenplace.net/2009/04/27/using-goto-for-error...
- asveikau 14y agoHaving worked in a large C code base that was occasionally tainted with this approach (rooted only because people have been told to avoid goto as dogma), I have to say that goto is a better approach to emulate try-finally or RAII in C. For one, the goto will read better as a single piece of prose, there will be no need to glance over at some other function to see the free call. Second, let's say your function has 2 allocations and a lock acquisition - that means your cleanup function needs a pointer to each, usually done with parameters. Add an extra allocation? New parameter to the cleanup function. This gets messy, fast, in a way that the goto does not.