Macros : Reference > Instructions > Looping Instructions >

Breaking out of a loop with the  BREAK  Keyword

Return to Introduction  Previous page  Next page  

The break command is used inside either a for or a while 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 FindHolidayOnDate(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 (see example below) :

 

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 FindHolidayOnDate(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 syntaxically 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. The while lop on the other hand verifies its condition anew on every iteration, so making that condition false is the cleaner solution.

 

See also : Assert, RaiseError.


Topic 108198 updated on 06-Nov-07
Topic URL: http://www.qppsupport.net/webhelp/index.html?breakingoutofaloopwiththebreak.htm