Created
January 31, 2025 06:36
-
-
Save vastus/26679f45a9450aeca1768fc4a2be4b00 to your computer and use it in GitHub Desktop.
defer in C (gcc only)
This file contains hidden or 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
#include <stdio.h> | |
#include <fcntl.h> | |
#include <sys/types.h> | |
#include <unistd.h> | |
#define CAT_IMPL(x, y) x##y | |
#define CAT(x, y) CAT_IMPL(x, y) | |
#define defer DEFER_IMPL(CAT(defer__, __COUNTER__)) | |
#define DEFER_IMPL(name) auto void name (void*); \ | |
int __attribute__ ((cleanup(name))) CAT(name, _var) = 42; \ | |
void name (void*) | |
void foo() | |
{ | |
int passwd_fd = open("/etc/passwd", O_RDONLY); | |
defer { | |
close(passwd_fd); | |
printf("closed passwd fd\n"); | |
} | |
int group_fd = open("/etc/group", O_RDONLY); | |
defer { | |
close(group_fd); | |
printf("closed group fd\n"); | |
} | |
printf("bye from foo()\n"); | |
} | |
int main(void) | |
{ | |
foo(); | |
return 0; | |
} |
Author
vastus
commented
Jan 31, 2025
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment