I have tried to break out of nested loops in a quite ineffective way:
BreakingPoint = false
a=["R1","R2","R3"]
b=["R2","R3","R4"]
for i in a
for j in b
if i == j
BreakingPoint = true
println("i = $i, j = $j.")
end
if BreakingPoint == true; break; end
end
if BreakingPoint == true; break; end
end
Is there an easier way to do that? In my actual problem, I have no idea about what are in arrays a
and b
, apart from they are ASCIIString
s. The array names (a
and b
in sample code) are also auto-generated through meta-programming methods.
Using break in a nested loop In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.
Method 1: Using the return statement Define a function and place the loops within that function. Using a return statement can directly end the function, thus breaking out of all the loops.
Break out of nested loops with else and continueYou can break all loops with else and continue . The code with explanation is as follows. When the inner loop ends normally without break , continue in the else clause is executed.
You can do one of two things
have the loop statement (if thats what its called) in a multi outer loop
for i in a, j in b
if i == j
break
end
end
which is clean, but not always possible
I will be crucified for suggesting this, but you can use @goto and @label
for i in a
for j in b
if i == j
@goto escape_label
end
end
end
@label escape_label
If you go with the @goto/@label way, for the sake of the people maintaining/reviewing the code, document your use properly, as navigating code with labels is breathtakingly annoying
For the discussion on the multi-loop break, see this
Put the 2D loop into a function, and do an early return
when you want to break
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With