Skip to content

Instantly share code, notes, and snippets.

@vastus
Created January 31, 2025 06:36
Show Gist options
  • Save vastus/26679f45a9450aeca1768fc4a2be4b00 to your computer and use it in GitHub Desktop.
Save vastus/26679f45a9450aeca1768fc4a2be4b00 to your computer and use it in GitHub Desktop.
defer in C (gcc only)
#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;
}
@vastus
Copy link
Author

vastus commented Jan 31, 2025

% gcc -Wall -Wextra -std=c23 -o defer defer.c && ./defer
bye from foo()
closed group fd
closed passwd fd

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