Named for loops?

Does Julia have a way of “naming” for loops so that one can break out of specific loops?

For example, I recently came across this example in Fortran:

program nestedLoop 
implicit none

integer:: i, j, k
   iloop: do i = 1, 3      
      jloop: do j = 1, 3         
         kloop: do k = 1, 3    
        
             print*, "(i, j, k): ", i, j, k               
         
         if (k==2) then
            exit jloop 
         end if
         
         end do kloop       
      end do jloop  
   end do iloop 
   
end program nestedLoop  

which produces

(i, j, k): 1  1  1
(i, j, k): 1  1  2
(i, j, k): 2  1  1
(i, j, k): 2  1  2
(i, j, k): 3  1  1
(i, j, k): 3  1  2

What would be the Julia equivalent?

You can use @goto and @label for this:

for i=1:3
    for j=1:3
        for k=1:3
            @info "indices" (i, j, k)
            if k == 2
                @goto end_j
            end
        end
    end
    @label end_j
end  

(There may eventually be more direct support for this in the language; for example see the old discussion at https://github.com/JuliaLang/julia/issues/5334).

5 Likes

Oh nice, it has been added to the 1.x milestone!

don’t hold your breath, milestones move frequently :wink: