Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of goto to continue from several nested loops C

Tags:

c

loops

goto

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?

like image 949
Cardstdani Avatar asked Oct 20 '25 15:10

Cardstdani


2 Answers

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).

like image 109
paxdiablo Avatar answered Oct 22 '25 04:10

paxdiablo


This is the one situation where goto is completely warranted. Go for it.

like image 29
wilx Avatar answered Oct 22 '25 05:10

wilx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!