Eight different approaches to implementing defer functionality in C are explored, ranging from compiler-specific solutions using GCC's cleanup attribute and nested functions to portable implementations using setjmp/longjmp or manual defer stacks. The C23/GCC version uses nested functions with cleanup attributes, while a GCC/Clang compatible version leverages Clang blocks. For broader compiler support, a stack-based approach manually tracks deferred calls, though it requires explicit initialization and custom return statements. A simplified GCC/Clang version drops block support in favor of single-function defers with automatic cleanup. Each approach involves tradeoffs between portability, ergonomics, and feature completeness.

9m read timeFrom antonz.org
Post cover image
Table of contents
C23/GCCC11/GCCGCC/ClangMSVCLong jumpSTCStackSimplified GCC/ClangFinal thoughts

Sort: