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

The Flag Variable pattern

The Flag Variable pattern

What you'll learn: How to use a simple integer variable as a "light switch" to track whether a specific condition has been met during your program's execution.

The logic of the lighthouse

Imagine you are standing on a shore at night, waiting for a single ship to arrive. You don’t need to count the waves or track the wind speed; you just need to know one thing: "Has the ship arrived yet?" You could keep a small lantern by your side. It stays off (0) all night until you spot the ship. The moment you see those sails, you light the lantern (1). Even if the ship later sails out of view, your lit lantern tells anyone who walks by later that the event definitely happened.

In C, this is the Flag Variable pattern. A "flag" is a variable (usually an int) that acts as a signal. It typically starts at 0 (false) and is "raised" to 1 (true) when a specific condition is met.

Implementation in code

This pattern is incredibly useful when searching through data. Because C doesn't have a built-in "search" command for arrays, you have to look at every item manually. A flag helps you remember if you found what you were looking for after the loop finishes.

#include <stdio.h>

int main() {
    int numbers[] = {12, 45, 7, 19, 30};
    int target = 7;
    int found = 0; // This is our "flag"

    for (int i = 0; i < 5; i++) {
        if (numbers[i] == target) {
            found = 1; // Raise the flag!
            break;     // No need to keep looking
        }
    }

    if (found) {
        printf("Target was found in the list.\n");
    } else {
        printf("Target was not found.\n");
    }

    return 0;
}

Why use a flag?

You might wonder, "Why not just print 'Found' inside the loop?"

If you print inside the loop, you might get five different messages (like "No, No, Yes, No, No"). By using a flag, you separate the process of searching from the result of the search. It allows your program to make a decision later on based on what happened earlier. It is the foundation of complex logic: gather the facts first, raise the flags, and then decide what to do next.

Key takeaway

A flag variable is a state-tracker that remembers if a condition occurred, allowing you to use that information after a loop or logic block has finished.