deepzero Posted February 3, 2011 Posted February 3, 2011 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?
Deathway Posted February 3, 2011 Posted February 3, 2011 (edited) Maybe a flag?bool bEscapeFlag = false;for(...){ for(...) { for(...) { if(...) { bEscapeFlag = true; break; } } if ( bEscapeFlag ) break; } if ( bEscapeFlag ) break;}done:... Edited February 3, 2011 by Deathway
deepzero Posted February 3, 2011 Author Posted February 3, 2011 yeah, but then the goto way looks cleaner to me
atom0s Posted February 3, 2011 Posted February 3, 2011 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.
Nacho_dj Posted February 3, 2011 Posted February 3, 2011 (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.CheersNacho_dj Edited February 4, 2011 by Nacho_dj
metr0 Posted February 4, 2011 Posted February 4, 2011 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.
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now