3 ms·
Error handling because you want to make a beeline to the handler, and memory management because you need it to be quick and goto is cheap?
by sliverstorm 15y ago
Error handling because you want to make a beeline to the handler, and memory management because you need it to be quick and goto is cheap?
- sparky 15y agoIn both cases, to avoid duplicating code. If you malloc() something in your function and intend on free()ing it before returning, it's often considered best practices to write the return block (which includes the free()s) once, and use "goto returnblocklabel" if you need to return early. So rather than this: void test() { int *x = malloc(1000); int *y = malloc(1000); for(int i = 0; i < 999; i++) { if(badThing) { free(x); free(y); return; } doStuff() if(otherBadThing) { free(x); free(y); return; } } free(x); free(y); return; } You'd have: void test() { int *x = malloc(1000); int *y = malloc(1000); for(int i = 0; i < 999; i++) { if(badThing) goto ret; doStuff() if(otherBadThing) goto ret; } ret: free(x); free(y); return; }
- Jach 15y agoI realize your example is contrived, but a simple 'break' statement (which in essence is a goto...) would work just as well. :) I somewhat vaguely recall a situation in my C class that I wanted to use goto to avoid duplicate code but the professor had previously threatened huge negative points if his scripts detected one. (That whole semester was just as much about conforming your code to his narrow specifics because "that's what happens in the real world." as learning C.)