3 ms·
Maybe that is exactly the problem, stop using a language designed in 1970's that ignored on purpose the ecosystem outside Bell Labs, unless where it is unavoida
by pjmlp 2y ago
Maybe that is exactly the problem, stop using a language designed in 1970's that ignored on purpose the ecosystem outside Bell Labs, unless where it is unavoidable.
And in such case, the C compiler doesn't have a limit to write functions and better modularize their implementations.
bool function_with_cleanup(void) {
int *buffer1 = NULL;
int *buffer2 = NULL;
FILE *file = NULL;
// Allocate first resource
buffer1 = malloc(sizeof(int) * 100);
if (!buffer1) {
return false;
}
// Allocate second resource
buffer2 = malloc(sizeof(int) * 200);
if (!buffer2) {
free(buffer1);
return false;
}
// Open a file
file = fopen("data.txt", "r");
if (!file) {
free(buffer1);
free(buffer1);
return false;
}
// Do work with all resources...
fclose(file);
free(buffer1);
free(buffer1);
return true;
}
Ah, but all those free() calls get tedious can be forgotten and mistyped
bool function_with_cleanup(void) {
int *buffer1 = NULL;
int *buffer2 = NULL;
FILE *file = NULL;
// Allocate first resource
buffer1 = arena_alloc(¤t_arena, sizeof(int) * 100);
if (!buffer1) {
return false;
}
// Allocate second resource
buffer2 = arena_alloc(¤t_arena, sizeof(int) * 200);
if (!buffer2) {
arena_reset(¤t_arena);
return false;
}
// Open a file
file = fopen("data.txt", "r");
if (!file) {
arena_reset(¤t_arena);
return false;
}
// Do work with all resources...
fclose(file);
arena_reset(¤t_arena);
return true;
}
Can still be improved with a mix of macros and varargs functions.
Or if using language extensions is a thing, the various ways to do defer in C.
- LtWorf 2y agoYou understand go doesn't have exceptions right?
- pjmlp 2y agoYou understand that I wrote C code, and in what concerns Go, panic/recover are exceptions that don't want to assume themselves as such?
- LtWorf 2y agoYou can't handle a panic, it's the whole point.
- 9rx 2y agoIn C, you mean? You clearly can in Go. How would you deal with exceptions otherwise? You can even get silly with it: func main() { try(func() { throw("Oops") }).catch(func(e any) { fmt.Println("Caught:", e) }) } https://go.dev/play/p/Y1-w9xUXIcO https://go.dev/play/p/Y1-w9xUXIcO