Skip to content

Instantly share code, notes, and snippets.

@izabera
Created October 16, 2016 19:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save izabera/e160fdaffe84aede805f054a56466aa3 to your computer and use it in GitHub Desktop.
Save izabera/e160fdaffe84aede805f054a56466aa3 to your computer and use it in GitHub Desktop.
SCOPE_EXIT macro in c
#ifndef __GNUC__
#error "nope"
#endif
#ifdef __clang__
#include <Block.h>
void __cleanblock(void (^*block)(void)) {
(*block)();
Block_release(*block);
}
#define SCOPE_EXIT \
void (^__end_of_scope_func)(void) \
__attribute__((cleanup(__cleanblock))) = ^
#else
#define SCOPE_EXIT \
auto void __end_of_scope_func(void *); \
int __end_of_scope_var __attribute__((cleanup(__end_of_scope_func))); \
void __end_of_scope_func(void *x __attribute__((unused)))
#endif
#include <stdio.h>
int main() {
SCOPE_EXIT {
puts("end of main");
};
puts("main scope");
{
SCOPE_EXIT {
puts("end of scope 1");
};
puts("scope1");
}
puts("still main scope");
{
SCOPE_EXIT {
puts("end of scope 2");
};
puts("scope2");
}
puts("main scope again");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment