Hacker News new | ask | show | jobs
by jstimpfle 1867 days ago
Some people like to make a defer macro like this:

     #define itervar(i) i##__LINE__
     #define FOR_DEFER(pre, post) for (int itervar(i) = ((pre), 0);
                               !itervar(i)++; (post))

     Foo *foos;
     FOR_DEFER(foos = alloc(Foo, 1024), free(foos))
     {
         // This "loop" only runs once.
     }
Those can be easily stacked

     FOR_DEFER(foos = alloc(Foo, 1024), free(foos))
     FOR_DEFER(bars = alloc(Bar, 1024), free(bars))
     {
          ///
     }
Here is a memory arena macro.

     #define FOR_MEMORY_ARENA(name) for DEFER(Arena name = make_arena(), free_arena(&arena))

     FOR_MEMORY_ARENA(arena)
     {
         Foo *foos = arena_alloc(&arena, Foo, 1024);
         Bar *bars = arena_alloc(&arena, Bar, 1024);
         // all allocations automatically freed at the end
     }
2 comments

gcc and llvm have a cleanup attribute you can use for this. Systemd uses it.

https://fdiv.net/2015/10/08/emulating-defer-c-clang-or-gccbl...

I guess you have to be careful not to return inside of these :)