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.

Read syntax diagramSkip visual syntax diagrambreak;

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 the PLAYBACK commands.
Examples
  • The following example shows a break command in the action part of a for command. If the i-th element of the array string is equal to '\0', the break command causes the for command to end.
    for (i = 0; i < 5; i++) {
       if (string[i] == '\0')
          break;
       length++;
    }
  • The following switch command contains several case clauses and one default clause. Each clause contains a function call and a break command. The break commands prevent control from passing down through subsequent commands in the switch body.
    char key;
    
    key = '-';
    AT LINE 15 switch (key)
    {
       case '+':
          add();
          break;
       case '-':
          subtract();
          break;
       default:
          printf("Invalid key\n");
          break;
    }