Created
April 13, 2025 19:13
-
-
Save mikesmullin/e492e096a2d20d49e7c893dba526a5bb to your computer and use it in GitHub Desktop.
Example of defer in C
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 <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