Jump to content
Tuts 4 You

breaking nicely out of nested loops


deepzero

Recommended Posts

Posted

hi,

everyone seems to hate on the use of "goto" commands in c/c++ and i dont like it too much myself, but i dont see any other way with nested loops:

good:


for(...)
{
if(...)
break;
}

not good:

for(...)
{
for(...)
{
for(...)
{
if(...)
goto done;
}
}
}done:
...

any "better" or "cleaner" way, avoiding the goto commmand? :)

Posted (edited)

Maybe a flag?


bool bEscapeFlag = false;
for(...)
{
for(...)
{
for(...)
{
if(...) {
bEscapeFlag = true;
break;
}
}
if ( bEscapeFlag ) break;
}
if ( bEscapeFlag ) break;
}done:
...
Edited by Deathway
Posted

yeah, but then the goto way looks cleaner to me :)

Posted

Goto is hated more or less so as it is seen as the lazy mans way out of coding more efficiently. Typically, if you are coding something that lands up requiring you to use Goto there is more or less so a better way to code what you are doing entirely. Such as your example, having nested loops further then two nests is typically bad practice or can be done more efficiently.

I personally don't use goto, but I don't see it being any different then asm having jumps to labels.

Posted (edited)

A good way of coding is secuencially, that is, every line of code is executed after the previous one has been executed. Using 'go to' causes this statement not to be true.

In fact, 'break' always escapes of the internal loop and you easily can follow where it goes: next to the last sentence of the loop.

Also, using goto is not much clear since a little change in its label could modify drastically the order of execution of instructions.

And goto was definitely dropped of good manners of coding specially because a person mantaining certain application not being its author could feel like in the hell by trying to understand the logical of such code full of 'goto' sentences, without any structural order...

So, I vote also for flags, very easy to use and understand for everybody even not knowing previously the sources.

Cheers

Nacho_dj

Edited by Nacho_dj
Posted

I personally like adding a flag to the for loop's condition, similar to what Deathway proposes:

for(int i = 0; !LeaveMeAlone && i < 123; i++) { ... }

Depends on when you want to break though. But well, I also prefer multiple indents and if-clauses where others would use goto instead.

I'd recommend flags as well, Nacho got a point - readability, 'cleaner' code flow.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...