Course contentsShow
← C
Lesson 295 of 1,2194. Control FlowFree lesson

The performance impact of loop controls

The performance impact of loop controls

What you'll learn: How to use break and continue to write more efficient code by reducing unnecessary CPU work.

The "Coffee Shop" Analogy

Imagine you are a barista looking for a specific customer’s order in a stack of 100 receipts. If you find the receipt on the 5th attempt, would you keep looking through the remaining 95? Of course not—that would be a waste of energy. In C, break is your way of telling the computer, "I found what I needed, stop looking."

Similarly, if you are checking a box of apples for bruises and you pick up one that is obviously a plastic toy, you don't need to inspect it for bruises. You just toss it aside and move to the next apple. That is what continue does: it skips the remaining work for the current item and jumps straight to the next one.

Saving CPU Cycles

Every line of code inside a loop takes a tiny amount of time to execute. When a loop runs millions of times, those tiny amounts add up.

Using break allows you to exit a loop early the moment a condition is met. This is vital for search algorithms. Without it, your program performs "dead work"—executing code that has no impact on the final result.

Using continue helps you skip heavy calculations for data that doesn't meet your criteria. By placing a continue check at the very top of your loop, you protect the rest of your logic from running on invalid or irrelevant data.

Code Example: Early Exit

Observe how we stop the loop immediately once our target is found, saving the computer from checking the rest of the array.

#include <stdio.h>

int main() {
    int numbers[] = {10, 20, 30, 42, 50, 60, 70};
    int target = 42;
    int found_at = -1;

    for (int i = 0; i < 7; i++) {
        // If we find it, stop immediately!
        if (numbers[i] == target) {
            found_at = i;
            break; // The remaining 3 iterations never happen
        }
        printf("Checking index %d...\n", i);
    }

    return 0;
}

Branch Prediction

While these keywords save work, overusing them in highly complex ways can sometimes confuse the CPU's "branch predictor" (its ability to guess what happens next). However, for most C programs, the performance gain from avoiding unnecessary iterations far outweighs these minor technicalities.

Key takeaway

Use break to stop work as soon as a goal is reached and continue to skip useless processing, ensuring your program only spends energy on meaningful calculations.