Break statement

The break statement in C interrupts the execution of the most inner loop or switch. If you use it in a nested structure (loop inside loop or switch inside loop or loop inside switch) it will terminate the inner block.



We can use break in all standard loops in C – while, do.. while, for.

Break statement – terminating a loop

This code will ask us to input numbers and will echo them back to us. When we input 0, the break will stop the execution of the for loop. This example will work the same way with a while or do..while loops.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
int main()
{
    printf("Please, input numbers. Input 0 to stop.\n");
    for(;;)
    {
        int input;
        scanf("%d", &input);
        if(input == 0)
            break;
        printf("%d\n", input);
    }
    return 0;
}

Terminating a switch

We use break inside a switch to stop the execution after a particular case. In the next example we want to print the day of the week for a given number (1-Monday, 2-Tuesday…).
If we omit break, the execution of the program will continue with the next case. Sometimes we use this to combine similar cases like in this example we combine the two weekend days:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
int main()
{
    int day;
    printf("Please, input a number for a day of the week!\n");
    scanf("%d", &day);
    switch(day)
    {
       case 1:
           printf("Monday");
           break;
       case 2:
           printf("Tuesday");
           break;
       ......
       case 6:
       case 7:
           printf("Weekend");
           break;
    }
    return 0;
}

Breaking out from nested constructions

If we put break in nested constructions, it will interrupt the inner most block. Then the program continues with the next line of code of the outer block. In the next example we nest a switch in a do..while loop. The same rule applies if we nest two loops.

Source code:

C - using break statement in nested blocks

In this case the break statements will only interrupt the cases. They will not interrupt the execution of the do..while loop. If we want to use a break for the loop, we have to write it outside of the switch block.

Where NOT to use the break statement

The keyword break can be used only inside a loop or a switch. It will not stop the execution of a random block of code(for instance an if). This will produce an error. Here is an example of wrong usage:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
int main()
{
    if(some condition)
    {
        some code here...
        break;
        some code here...
    }
    return 0;
}

If you want to stop the execution of a block outside of loop, you can use the goto statement.

See also:

    - Loops – for, while, do..while
    - switch
    - goto

   Search this site: