break and continue
The sensor's data is messy. A failed sample is recorded as -999, and the list of readings ends with a marker value, 9999, after which nothing is real data. The logger must skip the bad samples, stop at the marker, and total everything else. Two small keywords steer the loop through all of it, and this lesson brings the whole course together.
The rule
continue skips to the next lap; break leaves the loop entirely.
continueabandons the rest of the current pass. In aforloop, the step expression (such asi++) still runs, then the test. In awhileordoloop, control goes straight to the test.breakleaves the innermost enclosing loop orswitchat once. Execution carries on after it.
Here is the logger's cleaning loop, using everything from the course: fixed-width integers, initialization, comparisons, a for loop and a cast:
#include <stdint.h>
#include <stdio.h>
int16_t readings[6] = {212, 215, -999, 219, 9999, 230};
long total = 0;
int used = 0;
for (int i = 0; i < 6; i++) {
if (readings[i] == -999) continue; /* bad sample: skip it */
if (readings[i] == 9999) break; /* end marker: stop here */
total += readings[i];
used++;
}
if (used > 0) {
printf("%d readings, average %.1f C\n", used, (double)total / used / 10.0);
}It prints 3 readings, average 21.5 C: the total is 212 + 215 + 219 = 646 tenths, and 646 / 3 / 10 is about 21.53.
Two things break does not do:
- Inside a
switchthat sits inside a loop,breakleaves only theswitch. The loop keeps going. - In nested loops,
breakleaves only the inner loop. To escape both, set a flag that the outer loop checks, or move the loops into a function andreturn.
The shortcut
Ask of each special value: "Is there more good data after it?" Yes: continue past it. No: break out.
i = 0 and 1
212 and 215 are ordinary. total becomes 427, used becomes 2.
A while loop needs extra care: if the step lives at the bottom of the body, a continue jumps over it. In while (i < 5) { if (i == 2) continue; printf("%d", i); i++; }, the loop prints 01 and then gets stuck at i == 2 forever. Increment before the continue, or use a for loop, where continue still runs the step.
Drills
Answer fast — trust the rule.
After the cleaning loop in this lesson, what are total and used?
If the -999 test used break instead of continue, what would total and used be?
What does for (int i = 0; i < 5; i++) { if (i == 2) continue; printf("%d", i); } print?
A break sits inside a switch, which sits inside a for loop. What does it leave?
Remember
- continue skips to the next lap; break leaves the innermost loop or switch entirely.
- Shortcut: "is there more good data after it?" Yes means
continue, no meansbreak. - Trap: in a
whileloop,continuecan skip the step and loop forever;breakescapes only one level.
