Hey, I have a question about programming style, because in my current code I am using a bigger function which calls some smaller functions and all of these need to be error-checked. So something like this:
void bigFunction() {
/* some computations */
if(smallFunction1() == -1) {
free(mem1);
free(mem2);
fclose(file);
unlink(filename);
return -1;
}
if(smallFunction2() == -1) {
free(mem1);
free(mem2);
fclose(file);
unlink(filename);
return -1;
}
if(smallFunction3() == -1) {
free(mem1);
free(mem2);
fclose(file);
unlink(filename);
return -1;
}
/* more computations and stuff in biggerFunction */
}
I think you can clearly see my problem: The code after one of these functions fails is always the same, and I feel like repeating this coder again and again will make my code more and more unreadable.
How to deal with this problem? gotos came into my mind, but in my programming courses in university I was told never use gotos (though I forget the reason why...)
C
tag since such clean-up logic is much easier to get right in languages with higher-level constructs (RAII,using
,with
, ...)