Skip to content

Instantly share code, notes, and snippets.

@mikesmullin
Created April 13, 2025 19:13
Show Gist options
  • Save mikesmullin/e492e096a2d20d49e7c893dba526a5bb to your computer and use it in GitHub Desktop.
Save mikesmullin/e492e096a2d20d49e7c893dba526a5bb to your computer and use it in GitHub Desktop.
Example of defer in C
#include <stdio.h>
#include <stdlib.h>
int do_something(const char *filename) {
FILE *file = NULL;
char *buffer = NULL;
int result = -1;
file = fopen(filename, "r");
if (!file) {
perror("fopen");
goto defer;
}
buffer = malloc(1024);
if (!buffer) {
perror("malloc");
goto defer;
}
// Do something with the file and buffer
printf("File opened and buffer allocated.\n");
// Success
result = 0;
defer:
// defer-style defer
if (buffer) {
free(buffer);
printf("Buffer freed.\n");
}
if (file) {
fclose(file);
printf("File closed.\n");
}
return result;
}
int main() {
if (do_something("test.txt") != 0) {
printf("Operation failed.\n");
} else {
printf("Operation succeeded.\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment