On Tuesday, 1 October 2013 at 11:47:37 UTC, John Colvin wrote:
On Tuesday, 1 October 2013 at 11:40:35 UTC, Manu wrote:
I'd say 90% of the time I find goto useful is when I need to
bail from
nested loops. I've often wondered if something like break(2)
would be a
more elegant solution to the breaking out of nested loops
problem.
labeled statements to the rescue!
outer: foreach(i; 0..10)
{
foreach(j; 0..10)
{
break outer;
}
}
break outer; Obsoletes one of my "only" use cases where before, I
would have used a goto instead:
foreach(i; 0..10)
{
foreach(j; 0..10)
{
goto double_break;
}
}
double_break: {}
It's awesome.
Too bad you can't break from an arbitrary block though. It can
help avoiding the dreaded "if(if(if(if(...))))" pattern, as well
as the "bool didYouDoIt" pattern. I still have to use my "goto
after_block" pattern :/
//----
//Search and deal with a specific condition
//While doing something special if the condition is not found.
{
if (some_condition) goto block_end; //No need to do anything
if (some_other_condition) goto block_end; //No need to do
anything
if (some_third_condition) goto block_end; //No need to do
anything
for (...)
{
for (...)
{
if (...)
{
do_processing();
goto block_end; //We found what we wanted.
}
}
}
do_code_for_not_found_here();
}
done_processing: {}
//Keep going here
//----
I guess I can always use the "do{}while(false);" pattern, but I
actually find it *more* confusing (IMO)