Flag Variable

A flag variable is a boolean set, reset, and tested at arbitrary locations in a program to control flow indirectly.

Why are flag variables bad?

Flag variables are the variable equivalent of goto — they can be mutated from anywhere and read anywhere, so the program’s control flow is smeared across data state instead of being visible in the code structure. In theory they can simulate any multi-exit loop, but the resulting code is cumbersome and hard to read.

Example: same logic, two ways

With flag variables (bad):

bool flag1 = false, flag2 = false;
while ( ! flag1 && ! flag2 ) {
    S1
    if ( C1 ) flag1 = true;
    else {
        S2
        if ( C2 ) flag2 = true;
        else { S3 }
    }
}
if ( flag1 ) E1;
else E2;

With a multi-exit loop (good):

for ( ;; ) {
    S1
    if ( C1 ) { E1; break; }
    S2
    if ( C2 ) { E2; break; }
    S3
}

The second version reads top-to-bottom — every exit is visible at loop scope, no flag state to track.

When flag variables are actually necessary

Sometimes they are — e.g. when the exit condition depends on state accumulated across iterations and must be re-tested after the loop. But reach for them last, not first.

In coroutines

Coroutines make flag variables even more unnecessary: suspend/resume naturally encodes execution state, so explicit flags that “remember where we were” are a code smell.