4 ms·
The primary use-case of defer (cleaning up resources) can be done with __attribute__((__cleanup__(<destructor>))). This effectively allows you to do RAII in C,
by cyphar 7y ago
The primary use-case of defer (cleaning up resources) can be done with __attribute__((__cleanup__(<destructor>))). This effectively allows you to do RAII in C, though it does require some careful thought when copying variables (you need to "move" them a-la Rust).
But the really classic way of doing "defer" in C is to do what Linux does:
int foo(void)
{
char *ptr = malloc(13);
int error = 0;
error = bar();
if (error < 0)
goto out_free;
// do something else
out_free:
free(ptr);
return error;
}
Once you get used to it, it feels very natural to write and understand.