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