Skip to content

Instantly share code, notes, and snippets.

@itod
Created June 19, 2015 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save itod/ae269e123cf94e42ccff to your computer and use it in GitHub Desktop.
Save itod/ae269e123cf94e42ccff to your computer and use it in GitHub Desktop.
Try/finally cleaner than multiple gotos with label?
void myfunc() {
void *thing1 = NULL;
void *thing2 = NULL;
@try {
thing1 = allocThing1();
if (!thing1) return;
// …use thing1 maybe
if (somethingWentWrongWithThing1) return;
// …use thing1 more maybe
thing2 = allocThing2();
if (!thing2) return;
// …use thing2 and maybe thing1
if (somethingWentWrongWithThing2) return;
// …use thing2 more and maybe thing1 more
} @finally {
if (thing1) deallocThing1(thing1);
if (thing2) deallocThing2(thing2);
}
}
@itod
Copy link
Author

itod commented Jun 19, 2015

One might even argue that try/finally is less awkward than gotos with a label...

@owensd
Copy link

owensd commented Jun 19, 2015

void myfunc() {
    void *thing1 = NULL;
    void *thing2 = NULL;

    thing1 = allocThing1();
    if (!thing1) goto cleanup;

    // …use thing1 maybe

    if (somethingWentWrongWithThing1) goto cleanup;

    // …use thing1 more maybe

    thing2 = allocThing2();
    if (!thing2) goto cleanup;

    // …use thing2 and maybe thing1

    if (somethingWentWrongWithThing2) goto cleanup;

    // …use thing2 more and maybe thing1 more

cleanup:
    if (thing1) deallocThing1(thing1);
    if (thing2) deallocThing2(thing2);
}

I think this is more standard, cleaner, and portable. Also, there is no runtime overhead cost associated with this.

@itod
Copy link
Author

itod commented Jun 19, 2015

I was responding only to a claim that goto was less awkward than try/finally. Which I think is not true. Neither of us made any claims about runtime overhead or cost of any kind :)

And I honestly think reasonable people can disagree on which looks "cleaner" or less "awkward". I'd say the try/finally wins there. It's certainly more structured. But then, I'm used to seeing this in Java.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment