cloopsgoto

Use of goto to continue from several nested loops C


I have a code in C that runs in an infinite while loop. Inside it, it has several nested loops performing some tasks. But at a certain point inside the inner for loop, for error handling purposes I'm forced to continue the execution on the next iteration of the outer while.

main_loop:
    while (1) {
        //Some functionalities...
        for (j = 0; j < num; j++) {
            for (k = 0; k < num; k++) {
                goto main_loop; // Continue the while loop
            }
        }
    }

If I write continue;, it continues the for iteration. I know I can add some flags to control the execution flow of all loops and modify those flags to implement the continue operation. But I finally decided to use a goto sentence to break the inner loops and continue to the desired iteration of while.

As goto can lead to spaghetti code situations, I'm wondering if this use-case of goto is sufficiently justified for being correct or is there any other specific way to continue the outer loop in similar codebases in C?


Solution

  • Your question actually contains it's own answer:

    As goto can lead to spaghetti code situations, ...

    The main problem of things like goto is that they may lead to unreadable code, not that they always do. People who blindly refuse to use language features, because they don't understand this, are doing themselves a disservice.

    Another example is is the fail-fast strategy where you check required conditions at the start of a function and simply return an error if they're not all met. The people who despise multiple return points in a function often get apoplectic when they see that, often a good reason to slip it into pull request in my opinion :-)

    And yet, in that case and yours, the code they arrive at in order to follow the "rules" is often less readable.

    Bottom line, there are certainly guidelines for a reason. But, unless you know why those reasons exist and apply sense to them, you're not really a artisan (I use that word because the same reasoning actually applies to a great many fields of endeavour).