16

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 ASCIIStrings. The array names (a and b in sample code) are also auto-generated through meta-programming methods.

kometen
  • 6,536
  • 6
  • 41
  • 51
zyc
  • 427
  • 1
  • 4
  • 12

2 Answers2

28

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

isebarn
  • 3,812
  • 5
  • 22
  • 38
  • 7
    There is really nothing more unreadable about the labels than with named `break` or with random booleans. As long as it's not misused, `@goto` and `@label` have an unwarranted negative reputation. Some programmers go so far to avoid them that they end up making code even less unreadable, as they replace a `@goto` with a boolean soup – Fengyang Wang Sep 30 '16 at 19:10
  • 2
    I share your opinion, i like using labels, and rarely use boolean locks, as they feel clumsy – isebarn Sep 30 '16 at 19:37
  • 1
    I like this answer, but had to chuckle at "I will be crucified for saying this..." :-D. Obligatory: https://xkcd.com/292/ – Dave C May 04 '18 at 21:15
  • That's what @goto is all about. Also in C. – Israel Unterman Feb 09 '21 at 12:46
19

Put the 2D loop into a function, and do an early return when you want to break.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117