Please enable JavaScript to view this site.

 

Navigation: Macros > Macro Language > Instructions > Looping

Breaking out of a Loop with the BREAK Keyword

Scroll Prev Up Next More

The break command is used inside either a for or a while loop, to interrupt that loop. As its name suggests, this commands breaks out of the loop to the line immediately after the endfor or endwhile.

 

If you wish to skip the remainder of an iteration, but not to stop looping, you should use the continue keyword instead.

 

Using break to interrupt a loop

// list the first holiday of each month for current year
nYear = YearOf(Today()) // get the current year
// loop through all 12 months
for nMonth = 1 to 12 step 1
   // for each month get 1st and last date
   nFirst = FirstDateOfMonth(nYear , nMonth)
   nLast  = LastDateOfMonth( nYear , nMonth)
   // loop through the days of the month
   for nDate = nFirst to nLast step 1
      if FindNextHolidayOnDate(nDate, nCurHolidaysSetId)
         // as soon as you find one, go to next month
         sRESULT = sRESULT + EvalToken(nDate,'[d] [mmm]')
         break // only want first holiday of the month
      endif
   endfor
endfor

In the above example note that we break out of the inner loop, but this does not affect the outer loop. If we had wanted to break out of both loops we would have added a variable to record the fact that we had broken out of the inner loop, and used it to break out of the outer loop, as in the next example.

 

Using break to interrupt nested loops

// list the first holiday of each month for current year
nYear = YearOf(Today()) // get the current year
// loop through all 12 months
for nMonth = 1 to 12 step 1
   // for each month get 1st and last date
   nFirst = FirstDateOfMonth(nYear , nMonth)
   nLast  = LastDateOfMonth( nYear , nMonth)
   // loop through the days of the month
   for nDate = nFirst to nLast step 1
      if FindNextHolidayOnDate(nDate, nCurHolidaysSetId)
         // as soon as you find one, go to next month
         sRESULT = sRESULT + EvalToken(nDate,'[d] [mmm]')
         bFoundIt = true
         break // only want first holiday of the month
      endif
   if FoundIt
      break
   endif
   endfor
endfor

Although it is syntactically correct to use a break inside a while loop, it is not as common.

 

The break command is often needed in a for loop which, due its unmodifiable parameters, is kind of on auto-pilot. On the other hand, the while loop verifies its condition anew on every iteration, so making that condition false is the cleaner solution (ie. easier for someone else to read at a later date).

 

See also: for loops, while loops, continue interruption.

 


Topic 108198, last updated on 18-Apr-2020