Search code examples
cgoto

How to avoid GOTO in this code


This is a derivate of C, so please don't get all angry that it doesn't look correct. It is indeed correct in this implementation.

I have this code:

func() {
    if (handler_1()) goto good;
    if (handler_2()) goto good;
    if (handler_3()) goto good;

    print("BAD");
    goto done;

good:
    print("GOOD");
    goto done;

done:
    print("DONE");
    // do some common stuff
}

I am not particularly happy with the gotos and labels, so I tried to use a do-while instead, but one GOTO is still left.

func() {
    do {
        if (handler_1()) break;
        if (handler_2()) break;
        if (handler_3()) break;

        print("BAD");
        goto done;
    } while(false);

    print("GOOD");

done:
    print("DONE");
    // do some common stuff
}

Note - the language does not use short circuit evaluation:

handler_1() || handler_2() || handler_3()

Would execute always all three handlers before checking the return values. I do not want that.

Available structures: SWITCH, GOTO, LABEL, FOR, WHILE, DO-WHILE, IF_ELSEIF_ELSE. It's also possible to make local variables.

Any ideas how to rewrite this code without using GOTO?


Solution

  • I'd recommend using a similar syntax to what you often see in the linux kernel.

    func() {
        if (!handler_1())
            goto fail;
        if (!handler_2())
            goto fail;
        if (!handler_3())
            goto fail;
    
        print("success");
        return 0;
    
    fail:
        print("failure");
        return -1;
    }