Breaking and Continuing a Loop
A break exits the nearest loop. A continue skips the rest of the current iteration and proceeds according to that loop's rules.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 2 min
In this article4 chapters
Follow three records
Given one empty row, one valid row, and one stop line, a loop can skip the empty row, process the valid row, and break on the stop line. A sentinel check identifies that final record explicitly.
Count before and after
If a counter is updated before checking emptiness, it counts all visited rows. If it is updated after the continue decision, it counts only processed rows. Trace those two values and name them separately when the report needs both. Counting events gives the update a single intended meaning.[1]
Trace each control transfer across one loop
A reader sees an empty row, a valid row, a stop marker, and another valid row. The empty row can use continue to skip parsing while leaving the loop ready to read again. The valid row is processed. A break at the marker exits the loop, so the last row is never seen. If a received count increments before checking the marker, it can include the marker. A saved count should increase only after action succeeds. Loop counters explains why update placement changes the result.
Watch the nearest enclosing structure
Breaking from an inner loop exits only that loop, whereas returning from a helper ends the entire call. In a nested grid search, a break on the matching column can still allow the outer loop to proceed to another row. Compare stopping a nested search.
Write test inputs with a skip first, a stop before a later ordinary item, and no stop at all. Assert the ordered processed records and any final output. Also check whether a while-loop continue bypasses the update deciding when the loop ends. A for loop over a normal finite iterator advances according to its own rules, while a while loop often relies on an explicit state change.