Hacker News new | ask | show | jobs
by Someone 534 days ago
> using goto, which indeed is the only available mechanism.

There are other options, but none of them is better, IMO. You can use nested functions:

    char * p = malloc(10);
    if(p!=0) {
      doTheRealWork(p);
    };
    free(p);
In gcc, doTheRealWork can be a nested function or it you can force them to be inlined.

You can also (more readable than that first alternative, IMO) wrap code in a single-iteration for or while loop and then use break to exit it:

  char *p = null;
  for(int i=0;i==0;i=1) {
    p = malloc(10);
    if(p==0) break;
    …
  }
  free(p);
Both will get uglier if you need to free multiple resources, but will work.