Breaking from all loops?

Started by
35 comments, last by Muppi 20 years ago
quote:Original post by Damocles
for (loop1)for (loop2)for (loop3)  if (someCondition)  {  break;  break;  break;  } 
The last two breaks are redundant; the code path never gets there. In short, it doesn''t work.

Use goto.

Advertisement
quote:Original post by lonesock
The original post asked about breaking out of nested loops: there is no indication that the function ends there, so I think the "return" based responses may not be what Muppi is asking for (nesting your nested loops in another function?


Well, as I said in my post, there''s a great chance that your function does too many things, if you need some postprocessing after the loops and that your design would be much cleaner if you breaked it up in two functions instead. It could be inlined if performance is an issue.

In my experience it''s very rare to really need postprocessing after nested loops. You should really think about your design if you need that. Ask yourself, do my function do more than one thing? Does it do exactly what the name tells?

Of course there are very rare cases were having it''s own function doesn''t make sense and then goto is the best option, but during my last ten years programming, I can''t remember any. Care to give any real world examples?
There was an article, once, titled: "''Goto considered harmful'' considered harmful."

What the OP describes is one of the very few situations where a goto is an acceptable, and probably one of (if not the) best solutions.
My stuff.Shameless promotion: FreePop: The GPL god-sim.
I don''t see why there should be any problem using goto within a small block of code.

And as for stack problems... I think that has already been put to rest, but aren''t compilers better than that nowadays?
quote:Original post by fractoid
What language?

If Java or C++, you can use exceptions. Or, if you don''t mind people looking at you funny, you can use goto.


DON''T! Exceptions are very slow, so don''t use them in a time-critical loop.
Goto is a perfectly valid language construct. For error handling, and labeled breaks, it''s invaluable. When you use goto to make your code easier to read, smaller, and cleaner, it''s a Good Thing. Goto is not inherently evil; it''s just one of the more popular tools used by evil programmers, so it often suffers from guilt by association.
enum Bool { True, False, FileNotFound };
/me votes for goto

Loop sentinels are ugly. Using exceptions for this is even uglier.

--
AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.
[Project site] [Blog] [RSS] [Browse the source] [IRC channel]
--AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.[Project site] [IRC channel] [Blog]

This topic is closed to new replies.

Advertisement