Implementing Scoped Defer in C
btmc.substack.com
btmc.substack.com
Why "(ab)use" goto ? Use it with pleasure! Solution from Linus Torwalds:
int somefunc(...) {
int ret = E_OK;
FILE *a = NULL;
FILE *b = NULL;
FILE *c = NULL;
if(!(a == fopen("a.txt",...)) {
ret = E_A_FAILED;
goto end;
}
if(!(b == fopen("b.txt",...)) {
ret = E_B_FAILED;
goto end;
}
if(!(b == fopen("b.txt",...)) {
ret = E_C_FAILED;
goto end;
}
/* do your fancy stuff here */
end:
if(a)
fclose(a);
if(b)
fclose(b);
if(c)
fclose(c);
return ret;
}
1. This code is clean and neat.2. People should read Linux kernel source code as their go to sleep Bible verse.
And severely flawed. The (a == fopen...), etc, are certainly not doing what is apparently intended.