‹ BackHN Continuity

Thread

Small programming tricks

681 points · 294 comments · signa11

  1. quietbritishjim · · focus · HN ↗
    This will probably seem to obvious to mention to many, but it took me a few years to realise that you could replicate the "BREAK XYZ" from languages of yesteryear:

       FOR I = 1 TO 10
           FOR J = 1 TO 10
               FOR K = 1 TO 10
                   DOSOMETHING I, J, K
                   REM Breaks out of the middle loop, continues next I iteration
                   IF SOMECONDITION(I, J, K) THEN BREAK J
               NEXT K
           NEXT J
       NEXT I
    
    in modern languages by refactoring the loop you want to break out of into a function and using return instead:

       def inner_loops(i):
           for j in range(10):
               for k in range(10):
                   do_something(i, j, k)
                   if some_condition(i, j, k):
                       return
       
       def fn():
           for i in range(10):
               inner_loops(i)
    1. dhosek · · focus · HN ↗
      Ugh, TIL that Python doesn’t have labeled breaks. Now I’m wondering what other languages in current use don’t have this functionality.
      1. elboru · · focus · HN ↗
        I was about to mention C#, but I just checked and it’s coming to C# 15 in a couple of months.
      2. jcranmer · · focus · HN ↗
        C added it to the C2y draft about a year ago (so not in any actual released version of C). C++ is still working on adding it to the C++ draft.
Open on Hacker News to reply ↗

Unofficial Hacker News client; not affiliated with Y Combinator.