break and continue
continue skips the rest of the current iteration and moves to the next, while break leaves the innermost enclosing loop or switch entirely.
Compare skipping one iteration with leaving the loop altogether.
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.