I think the following code is normal (and malloc/free is similar):
int foo(){
FILE *fp = fopen("test.in", "r");
int i;
for(i = 0; i < NUM; i ++){
if(Match(fp, i)){
fclose(fp);
return i;
}
}
fclose(fp);
return 0;
}
As we can see fclose(fp) appears twice in the code. It will appear more if there are other return statements in the function foo. However, it is troublesome that I have to write fclose(fp) many times. One solution is just one return for one function. However, multiple returns is sometimes useful. Is there any other solution?
PS: As I know, there is a macro(with-open-file) in lisp.
(with-open-file (stream-var open-argument*)
body-form*)
It could open and close file for us.
In the source code of linux kernel, there are many functions that have to take care of locks and other resource on return. And they conventionally add a cleanup label at the end of the function, and
gotothere whenever early return occurs. I personally recommend this usage to avoid duplicate code, and maybe this is the only sane usage ofgoto.