Goto Cleanup

suggest change

In C++ code bases which used to be C, one can find the pattern goto cleanup. goto makes the control flow harder to follow, so it is often avoided. Early returns still have to release resources, which is why the goto jumps to one shared cleanup block. TRUE and FALSE below are not C++ keywords; the fragment assumes macros or constants with those names.

short calculate(VectorStr **data) {
    short result = FALSE;
    VectorStr *vec = nullptr;
    if (!data)
       goto cleanup;  //< Could become return false

    // ... Calculation which allocates with new VectorStr[n]

    result = TRUE;
cleanup:
    delete [] vec;
    return result;
}

In modern C++, use RAII through a standard owning type:

#include <memory>

bool calculate(VectorStr **data) {
    std::unique_ptr<VectorStr[]> vec;
    if (!data)
       return false;

    // ... Allocate with std::make_unique<VectorStr[]>(size) and store it in vec.

    return true;
}

If the allocation represents a resizable sequence, prefer std::vector over an owning array.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents