From the book "Linux Device Drivers".

Error recovery is sometimes best handled with the goto statement. We normally hate to use goto, but in our opinion, this is one situation where it is useful. Careful use of goto in error situations can eliminate a great deal of complicated, highly-indented, “structured” logic. Thus, in the kernel, goto is often used as shown here to deal with
errors.

The following sample code (using fictitious registration and unregistration func-
tions) behaves correctly if initialization fails at any point:

int __init my_init_function(void)
{
    int err;
    /* registration takes a pointer and a name */
    err = register_this(ptr1, "skull");
    if (err) goto fail_this;
    err = register_that(ptr2, "skull");
    if (err) goto fail_that;
    err = register_those(ptr3, "skull");
    if (err) goto fail_those;
    return 0; /* success */
    fail_those: unregister_that(ptr2, "skull");
    fail_that: unregister_this(ptr1, "skull");
    fail_this: return err; /* propagate the error */
}

This code attempts to register three (fictitious)facilities. The goto statement is used in case of failure to cause the unregistration of only the facilities that had been suc-
cessfully registered before things went bad.

On 26/9/22 10:17, David Crayford wrote:

On 26/9/22 10:13, Steve Smith wrote:
lol... We definitely need a guide to refracturing code.

More seriously, a decent commentary on how to use goto "correctly" would be
a nice thing to see.
Here you go, just in case you missed it the first time I posted https://koblents.com/Ches/Links/Month-Mar-2013/20-Using-Goto-in-Linux-Kernel-Code/

----------------------------------------------------------------------
For IBM-MAIN subscribe / signoff / archive access instructions,
send email to [email protected] with the message: INFO IBM-MAIN

Reply via email to