Subject: Re: release time?

Re: release time?

From: Alexander Lamaison <swish_at_lammy.co.uk>
Date: Thu, 21 Jan 2010 21:22:11 +0000

2010/1/21 Peter Stuge <peter_at_stuge.se>:
> Alexander Lamaison wrote:
>> > Would anyone veto changes that reduce mindless code duplication such
>> > as above with the use of forward gotos to the end of functions?
>>
>> Rather than gotos, how about a helper function e.g.:
>
> A function brings a new scope which may not always work. goto is not
> a bad thing if used right. I think forward gotos for error handling
> is an excellent way to keep code clean, coherent and short:
>
> main() {
>  int ret=1;
>  char *ptr=NULL;
> ..
>  if(some_error)
>    goto done;
>  ptr=malloc(1024*1024);
>  if(NULL==ptr) {
>    perror("malloc");
>    goto done;
>  }
>
>  /* main stuff */
>  ret=0;
>
> done:
>  if(ptr)
>    free(ptr);
>  return ret;
> }
>
>
>> Or am I missing the need for gotos (not got the code in front of me)?
>
> Cleaning up ptr in the above example is the point. Instead of
> duplicating cleanup code in every single error handling branch within
> main stuff, all cleanup code is in one single location.

This should still be done with a function. Arguably, that's what they
were invented for.

static int cleanup(char * ptr, int ret)
{
    if(ptr)
        free(ptr);
    return ret;
}

main() {
    int ret=1;
    char *ptr=NULL;
..
    if(some_error)
        return cleanup(ptr, ret);
    ptr=malloc(1024*1024);
    if(NULL==ptr) {
        perror("malloc");
        return cleanup(ptr, ret);
    }

    /* main stuff */
    return cleanup(ptr, 0)
}

This makes very clear what is being cleaned up when and where.
Passing the return code in and out of cleanup may look pointless in
this example but as a general technique it allows the cleanup process
itself to signal an error.

Alex
_______________________________________________
libssh2-devel http://cool.haxx.se/cgi-bin/mailman/listinfo/libssh2-devel
Received on 2010-01-21