Created
October 16, 2016 19:15
-
-
Save izabera/e160fdaffe84aede805f054a56466aa3 to your computer and use it in GitHub Desktop.
SCOPE_EXIT macro in c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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