Oh noooooo!!

Forrest Tanaka ftanaka at Apple.COM
Fri Sep 8 01:22:12 AEST 1989


In article <7598 at goofy.megatest.UUCP> djones at megatest.UUCP (Dave Jones) writes:
>About a year or two ago, I brazenly stated that I thought the
>goto-statement was not necessarily a hanging offense. I was astounded
>by the reaction. People posted messages stating flat out that I was
>an incompetent programmer, and that software from any company unfortunate
>enough ever to have had me on the payroll was suspect at best. They were
>adamant; rude, I thought. I pouted.

I've been using gotos regularly in my C code for quite a few months--in one
specific situation.  That situation is for error handling.  The usual sequence
is something like this (AllocateMemory just allocates some memory and returns
a pointer to it, or 0 if there isn't enough memory.  DeallocateMemory
deallocates that memory):

#define null 0

char *
SomeFunction ()
    {
    char *Block0;
    char *Block1;
    char *Block2;

    Block0 = (char *) null;
    Block1 = (char *) null;
    Block2 = (char *) null;
    if ((Block0 = AllocateMemory ()) == (char *) null)
        goto Abort;
    if ((Block1 = AllocateMemory ()) == (char *) null)
        goto Abort;
    if ((Block2 = AllocateMemory ()) == (char *) null)
        goto Abort;
    return Block0;

Abort:
    if (Block0 != (char *) null)
        DeallocateMemory (Block0);
    if (Block1 != (char *) null)
        DeallocateMemory (Block1);
    if (block2 != (char *) null)
        DeallocateMemory (Block2);
    return (char *) null;
    }

Now, never mind that Block1 and Block2 get lost when SomeFunction returns.
This is just an example of some calls that could be made.  Also, the last if
statement in the Abort block can never be true.  I'm just trying to be
consistent here.

When I was trying to come up with a consistent and convenient way to handle
error conditions within functions, I examined what I would do if I was writing
the function in assembly language.  I would probably check for an error when
a function like AllocateMemory returns, and if there was an error, branch to
some error handling code.  Ah hah! thought I.  This is is possible in C with
the goto statement.  Now I never have to have a bunch of nested ifs and I can
deal with undoing what I had done in that function before the error occured.

Or, how 'bout this justification: When something exceptional (like an error)
occurs, something exceptional (like a goto) should happen.
*******************************************************************************
Forrest Tanaka                            AppleLink: TANAKA
Macintosh Developer Technical Support     UseNet:    ftanaka at Apple.COM
Apple Computer, Inc.



More information about the Comp.lang.c mailing list