Search code examples
julianested-loops

How to break out of nested for loops in Julia


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.


Solution

  • 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