Skip to content

Instantly share code, notes, and snippets.

@baruch
Created May 27, 2018 19:09
Show Gist options
  • Select an option

  • Save baruch/f005ce51e9c5bd5c1897ab24ea1ecf3b to your computer and use it in GitHub Desktop.

Select an option

Save baruch/f005ce51e9c5bd5c1897ab24ea1ecf3b to your computer and use it in GitHub Desktop.
Defer cleanup for C (gcc and llvm)
#define DEFER_MERGE(a,b) a##b
#define DEFER_VARNAME(a) DEFER_MERGE(defer_scopevar_, a)
#define DEFER_FUNCNAME(a) DEFER_MERGE(defer_scopefunc_, a)
#define DEFER(BLOCK) void DEFER_FUNCNAME(__LINE__)(int *a) BLOCK; __attribute__((cleanup(DEFER_FUNCNAME(__LINE__)))) int DEFER_VARNAME(__LINE__)
// Usage:
/*
void dosomething()
{
char* data = malloc(100);
DEFER({ free(data); });
dosomethingwith(data);
}
*/
@g-berthiaume
Copy link

@sinecode
Did you manage to get rid of the warning: ISO C forbids nested functions [-Wpedantic] warning?

@martinfinke
Copy link

Try this https://godbolt.org/z/6Y8Ys4dPo

Any C version and any compiler.

Now simpler to re-use: https://godbolt.org/z/zsYre5Kfj

Problem with the for loop approach:

defer( close_file( dummsy_ )) {
    // Do something with the file
    if (/* something failed */)
        return;
    // ...and now close_file doesn't get called 🧨
} 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment