Give Me a break

I received an email question recently about the power of the break keyword. The answer to the question is that you can only break out of the current loop or switch-case structure. Even in a nested loop, or a switch-case structure within a loop, break affects only the current element.

Specifically, the reader wanted to know if a break inside switch-case structure would also halt the while loop if the structure were inside the loop. The answer is no.

This type of while/switch-case construction is common in many programs. I use it frequently in my code. Sometimes I use:

while(1)

But more frequently I use:

while(!done)

Where done is a boolean value, either TRUE (1) or FALSE (0).

The switch-case structure inside the while loop examines input. Each case part of the structure deals with a keypress or some other condition. One of the case items handles the loop’s exit condition. For example:

case 'q':
case 'Q':
     done = TRUE;
     break;

Above, on the q or Q input, the done variable is set to TRUE. The break statement exits the switch-case structure, but not the while loop. That loop terminates because the value of done is now TRUE.

For an endless while loop, some other condition must be set, because you need a break statement outside the switch-case structure to terminate the loop.

The following code example shows nested while loops. The break statements affects only the current loop:

#include <stdio.h>

int main()
{
    int x = 10;

    puts("main() function");
    while(x)
    {
        puts("First while loop");
        while(x)
        {
            puts("\tSecond while loop");
            x--;
            if(x<8)
                break;
        }
        if(x<5)
            break;
    }
    puts("Back in the main() function");

    return(0);
}

The output shows how the break statement at Line 16 in the inner loop doesn't cancel the outer while loop. Only the break statement at Line 19 does that. Here is the output:


main() function
First while loop
	Second while loop
	Second while loop
	Second while loop
First while loop
	Second while loop
First while loop
	Second while loop
First while loop
	Second while loop
Back in the main() function

One more thing about the break keyword: It can dwell only within a loop or switch-case structure. The compiler generates an error if you stick a rogue break in a function. In other words, you can't use break to exit a function or terminate a program.

Leave a Reply