break statement-break out of loop block or switch block

If you use break statement , for statement, while statement You can get out of the loop block of a> or the block of switch statement.

for (Initialize loop variable; Condition to loop; Update loop variable) {
  
  # Exit the loop block
  break;
}

while (condition to loop) {
  
  # Exit the loop block
  break;
}

switch (value) {
  case Case 1 value:
    // Exit the switch block
    break;
  case Case 2 value:
    // Exit the switch block
    break;
  case Case 3 value:
    // Exit the switch block
    break;
  default: default:
    // Processing in cases other than the above
}

Break statement sample code

This is a sample code that uses a break statement in a for statement. If the array contains a certain value, it is a process to exit using a break statement.

#include <stdint.h>
#include <stdio.h>

int main (void) {
  
  // arrangement
  int32_t nums [] = {3, 5, 9};
  int32_t nums_length = 3;
  
  int32_t match = 0;
  for (int32_t i = 0; i <nums_length; i ++) {
    // contains 5
    if (nums [i] == 5) {
      match = 1;
      break;
    }
  }
  
  if (match) {
    printf("Match\n");
  }
  else {
    printf("Not Match\n");
  }
}

Difference from Perl, a sentence that escapes the loop

The C language break statement corresponds to Perl's last statement.

Associated Information