Examples of good gotos in C or C++

Heres one trick I’ve heard of people using. I’ve never seen it in the wild though. And it only applies to C because C++ has RAII to do this more idiomatically.

void foo()
{
    if (!doA())
        goto exit;
    if (!doB())
        goto cleanupA;
    if (!doC())
        goto cleanupB;

    /* everything has succeeded */
    return;

cleanupB:
    undoB();
cleanupA:
    undoA();
exit:
    return;
}

Leave a Comment