C — Break statements
break immediately leaves the nearest enclosing loop or switch in C. Put it before a state change when a failed check should cancel that operation.
A simple example
Stop before printing 3
- Start with Visit 1 through 4
- Do this Leave at 3
- Result 1 → 2
#include <stdio.h>
int main(void) {
for (int n = 1; n <= 4; n++) {
if (n == 3) {
break;
}
printf("%d\n", n);
}
}
1 2
Stop before the first unaffordable job
Process the queue in order with a budget of 10. Stop the loop as soon as the next job would exceed the remaining budget. The array elements are visited in order. Updating the remaining budget only after the comparison keeps the rejected job out of both totals.
A print queue has ten credits and must serve jobs in arrival order. Jobs costing four and three leave three credits. The next job costs eight, so the queue stops before the smaller job behind it.
Run the example
Use a C17 compiler. Run these commands from the directory containing the example. Use a Unix-style shell.
cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lesson
#include <stdio.h>
int main(void) {
int costs[] = {4, 3, 8, 1};
int remaining = 10;
int accepted = 0;
for (int i = 0; i < 4; ++i) {
if (costs[i] > remaining) break;
remaining -= costs[i];
++accepted;
}
printf("%d accepted, %d left\n", accepted, remaining);
return 0;
}
2 accepted, 3 left
The first two jobs cost 4 and 3, leaving 3. The next costs 8, so processing stops before the later job costing 1.
Try it yourself
Replace the cost of 8 with 3. What changes?
Check your answer
The third job exactly fits. Three jobs are accepted and the remaining budget is zero. The last job cannot run.