by t43562 · 9mo ago · 0 comments
#define RETURN(x) result=x;goto CLEANUP
void myfunc() {
int result=0;
if (commserror()) {
RETURN(0);
}
.....
/* On success */
RETURN(1);
CLEANUP:
if (myStruct) { free(myStruct); }
...
return result
}
The advantage being that you never have to remember which things are to be freed at which particular error state. The style also avoids lots of nesting because it returns early. It's not as nice as having defer but it does help in larger functions.You also don't have to remember this when using defer. That's the point of defer - fire and forget.
There are several other issues I haven't shown like what happens if you need to free something only when the return code is "FALSE" indicating that something failed.
This is not as nice as defer but up till now it was a comparatively nice way to deal with those functions which were really large and complicated and had many exit points.
In other words, the first time you access a "freshly allocated" non-null pointer you may get a page fault due to insufficient physical memory.
result=x;
goto cleanup;
if you meant result=x;
goto cleanup;
At least then you'll be able to follow the control flow without remembering what the magic macro does.