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
      Reset_FindNextHolidayOnDate()
      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

// find the first holiday date of the current year
bFoundIt = false
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
      Reset_FindNextHolidayOnDate()
      if FindNextHolidayOnDate(nDate, nCurHolidaysSetId)
         // record the first holiday date found
         sRESULT = sRESULT + EvalToken(nDate,'[d] [mmm]')
         bFoundIt = true
         break // leave the inner date loop
      endif
   endfor
   if bFoundIt
      break // leave the outer month loop
   endif
endfor

Use break in either a for or a while loop when execution must leave the loop immediately. Changing a variable so that a while condition becomes false does not itself skip the remaining instructions in the current iteration: the condition is tested again at the start of the next iteration.

 

Choose between these approaches according to whether the remaining instructions should execute and which makes the code easier to understand.

 

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

 


Topic 108198, last updated on 09-Oct-2026