Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What to use instead of Goto Statements? [closed]

I'm wondering what I should be using instead of goto statements?

Should I be using nested if/while/do-while statements?

They say that using goto creates 'spaghetti code', but surely if someone is writing a large console application and they have if statement after if statement in an attempt to control the flow, that's going to make a mess?

I'm asking as many people have asked why the goto statement is bad, but not what to replace it with. I'm sure a lot of beginners could do with this.

This is for C++.

like image 407
Blake Wills Avatar asked Oct 27 '25 05:10

Blake Wills


2 Answers

You are much better off using functions, loops, and conditional statements. Use break and continue as necessary.

I can nearly guarantee you any situation in which you are utilizing goto there is a better alternative. There is one notable exception to this: multi-level break.

while(1){
    while(1){
        goto breakOut;
    }
    //more code here?
}
breakOut:

In this one (relatively) rare situation, goto can be used in place of a typical "break" to make it clear we are actually getting out of a nested loop. The other way to approach this is with a "done" variable:

while(!done){
    while(!done){
        done = true;
        break;
    }
    if(done){break;}
    //More code here?  If so, the above line is important!
}

As you can see, the done variable is more verbose when you have additional processing in outer loops, so a goto is a cleaner way of breaking free!

However, in 99% of cases you really, really, don't want to start writing a bunch of goto statements. Really think through each one.

With functions the above could also be written like so:

bool innerLoop(){
    while(1){
        return false;
    }
    return true;
}

...
while(innerLoop()){ //can only be written this way if the inner loop is the first thing that should run.
    //More code here?
}
...

Sometimes breaking an inner loop out in this way can be messy if there are a lot of dependencies on the outer one. But it remains a viable way of breaking out of code early with return statements instead of goto or break.

like image 76
M2tM Avatar answered Oct 29 '25 18:10

M2tM


Don’t listen to people who say "never use goto". You're quite right that there are cases where nesting scoped blocks will make a heck of a lot more mess than a goto. It has its place, just as a switch/case does. However, with functions you can often refactor away the entire argument and keep people happy.

like image 38
Lightness Races in Orbit Avatar answered Oct 29 '25 20:10

Lightness Races in Orbit



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!