2 ms·
In the C code I've written, I've found there's really one major, common use for goto: stack unwinding. It usually looks something like status_t foo (result
by sjolsen 11y ago
In the C code I've written, I've found there's really one major, common use for goto: stack unwinding. It usually looks something like
status_t foo (result_t (*result))
{
status_t status = good;
resource1_t r1;
if (failed (status = get_r1 (&r1)))
goto end;
resource2_t r2;
if (failed (status = get_r2 (&r2)))
goto cleanup_r1;
resource3_t r3;
if (failed (status = get_r3 (&r3)))
goto cleanup_r2;
status = get_result (result, r1, r2, r3);
cleanup_r3:
release_r3 (r3);
cleanup_r2:
release_r2 (r2);
cleanup_r1:
release_r1 (r1);
end:
return status;
}
Personally, though, I prefer using C++ and destructors (and, where appropriate, exceptions):
result_t foo ()
{
// Allow exceptions to propagate
auto r1 = get_r1 ();
auto r2 = get_r2 ();
auto r3 = get_r3 ();
return get_result (r1, r2, r3);
}
Exceptions aren't always appropriate, but the C++ still usually ends up a little cleaner. I would love to see something like Haskell's Maybe monad that lets you write code like the above, but returning status information instead of throwing exceptions.