break command (C and C++)
The break
command allows you to terminate and
exit a loop (that is, do
, for
, and while
)
or switch
command from any point other than the logical
end. You can place a break
command only in the body
of a looping command or in the body of a switch
command.
The break
keyword must be lowercase and cannot be
abbreviated.
In a looping statement, the break
command ends
the loop and moves control to the next command outside the loop.
Within nested statements, the break
command ends
only the smallest enclosing do
, for
, switch
,
or while
commands.
In a switch
body, the break
command
ends the execution of the switch
body and gives control
to the next command outside the switch
body.
Usage notes
- You cannot use the
break
command while you replay recorded statements by using thePLAYBACK
commands.
Examples
- The following example shows a
break
command in the action part of afor
command. If thei
-th element of the arraystring
is equal to'\0'
, thebreak
command causes thefor
command to end.for (i = 0; i < 5; i++) { if (string[i] == '\0') break; length++; }
- The following
switch
command contains severalcase
clauses and onedefault
clause. Each clause contains a function call and abreak
command. Thebreak
commands prevent control from passing down through subsequent commands in theswitch
body.char key; key = '-'; AT LINE 15 switch (key) { case '+': add(); break; case '-': subtract(); break; default: printf("Invalid key\n"); break; }