Swift

Emulating "defer" in C, with Clang or GCC+Blocks

In the Go language (and now Apple’s Swift), there’s a new control-flow mechanism: defer.

When you tag a function call with the defer keyword, its execution is deferred until the end of the current scope. This makes it easy to construct an ad-hoc use of the RAII pattern — handy for placing resource initialization and finalization next to each other, to make it less likely that you’ll forget to finalize a resource.

I was curious whether it was possible to do something similar in C. It turns out it’s pretty straightforward.