20 out of 28 rated this helpful Rate this topic

The break Statement

The break statement terminates the execution of the nearest enclosing loop or conditional statement in which it appears. Control passes to the statement that follows the terminated statement, if any.


break;

break is used with the conditional switch statement and with the do, for, and while loop statements.

In a switch statement, break causes the program to execute the next statement after the switch. Without a break statement, every statement from the matched case label to the end of the switch, including the default, is executed.

In loops, break terminates execution of the nearest enclosing do, for, or while statement. Control passes to the statement that follows the terminated statement, if any.

Within nested statements, the break statement terminates only the do, for, switch, or while statement that immediately encloses it. You can use a return or goto statement to transfer control from within more deeply nested structures.

The following example illustrates the use of the break statement in a for loop.

// break_statement.cpp

#include <stdio.h>

int main()
{
    int i;

    for (i = 1; i < 10; i++)
    {
        printf_s("%d\n", i);

        if (i == 4)
            break;
    }
}  // Loop exits after printing 1 through 4

Output

1
2
3
4
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
foreach too
In addition to the switch, do, for, and while statements mentioned above, break is also used with the foreach keyword.