4 ms·
An advantage of using goto to handle errors is that you don't need that condition checking in the teardown: int result = ERROR_CODE; FILE * f = NULL;
by ZoFreX 13y ago
An advantage of using goto to handle errors is that you don't need that condition checking in the teardown:
int result = ERROR_CODE;
FILE * f = NULL;
char * s = NULL;
if((f = open_file()) == NULL) goto end;
if((s = allocate_string() == NULL) goto closefile;
if((some_other_thing() == NULL) goto freestring;
...
result = NOERROR;
freestring:
free_string( s);
closefile:
close_file( f);
return result;
- kstenerud 13y agoThat's fine until you have multiple lines that goto closefile or freestring, and you mix them up at some point, or you try to refactor the code and forget to update one of your gotos. The resulting bug will wait beneath the waters until one day you get a mysterious "out of file descriptors" or "out of memory" error at some random place in your program after it's been running for awhile. And really, the extra condition check likely isn't going to affect the critical path, but it will make it a lot easier to reason about the code, especially when someone else has to modify it.
- ZoFreX 13y agoIt's really a matter of both taste and situation. I've seen some very compelling examples from the Linux kernel where this is definitively easier to follow than the alternatives (Linus has made some good defences of goto for this purpose), but I've never felt it was the clearest option in any code I've written myself.