Cprogramming 简明教程

Break Statement in C

break 语句在 C 中用于两种不同的上下文。在 switch-case 中, break 被放置在每个 case 块的最后一个语句处。 break 语句也可以被用在任意 loop constructs 的主体部分 ( whiledo–while 以及 for 循环)。

The break statement in C is used in two different contexts. In switch-case, break is placed as the last statement of each case block. The break statement may also be employed in the body of any of the loop constructs (while, do–while as well as for loops).

当在循环内部使用时, break 会导致循环终止。在 switch-case 语句中, break 在执行相应的 case 块后移出 switch 范围。

When used inside a loop, break causes the loop to be terminated. In the switch-case statement, break takes the control out of the switch scope after executing the corresponding case block.

Flowchart of Break Statement in C

循环中 break 的流程图如下 −

The flowchart of break in loop is as follows −

cpp break statement

以下流程图显示了如何在 switch-case 中使用 break −

The following flowchart shows how to use break in switch-case −

break statement flowchart

在两种情况下, break 都会导致移出当前范围。

In both the scenarios, break causes the control to be taken out of the current scope.

Break Statements in While Loops

break 语句从未无条件使用过。它总出现在 if statement 的 True 部分。否则, loop 将在第一次迭代中间终止。

The break statement is never used unconditionally. It always appears in the True part of an if statement. Otherwise, the loop will terminate in the middle of the first iteration itself.

while(condition1){
   . . .
   . . .
   if(condition2)
   break;
      . . .
      . . .
}

Example of break Statement with while Loop

以下程序检查给定的数字是否是质数。质数除了自身和 1 之外不能被任何其他数字整除。

The following program checks if a given number is prime or not. A prime number is not divisible by any other number except itself and 1.

while loop 将除数递增 1,并尝试检查它是否可以被整除。如果发现可以被整除,则 while 循环终止。

The while loop increments the divisor by 1 and tries to check if it is divisible. If found divisible, the while loop is terminated.

#include <stdio.h>

/*break in while loop*/
int main () {

   int i = 2;
   int x = 121;
   printf("x: %d\n", x);

   while (i < x/2){
      if (x % i == 0)
         break;
      i++;
   }
   if (i >= x/2)
      printf("%d is prime", x);
   else
      printf("%d is not prime", x);

   return 0;
}

执行此代码后,您将获得以下输出 −

On executing this code, you will get the following output −

x: 121
121 is not prime

现在,将 “x” 的值更改为 25 并再次运行代码。它将产生以下输出 −

Now, change the value of "x" to 25 and run the code again. It will produce the following output −

x: 25
25 is not prime

Break Statements in For Loops

你可以在 for loop 中使用 break 语句。通常, for 循环旨在执行一定次数的迭代。但是,有时可能需要在达到一定条件时中止循环。

You can use a break statement inside a for loop as well. Usually, a for loop is designed to perform a certain number of iterations. However, sometimes it may be required to abandon the loop if a certain condition is reached.

for 循环中使用 break 的情况如下 −

The usage of break in for loop is as follows −

for (init; condition; increment) {
   . . .
   if (condition)
   break;
      . . .
}

Example of break Statement with for Loop

以下程序在检测到元音 (a、e、I 或 u) 之前打印给定字符串中的字符。

The following program prints the characters from a given string before a vowel (a, e, I, or u) is detected.

#include <stdio.h>
#include <string.h>

int main () {

   char string[] = "Rhythmic";
   int len = strlen(string);
   int i;

   for (i = 0; i < len; i++){
      if (string[i] == 'a' || string[i] == 'e' || string[i] == 'i' || string[i] == 'o' || string[i] == 'u')
         break;
      printf("%c\n", string[i]);
   }

   return 0;
}

运行代码并检查其输出:

Run the code and check its output −

R
h
y
t
h
m

如果 break 出现在嵌套循环结构的内层循环中,它将中止内层循环并继续迭代外层循环体。对于下一次迭代,它将再次进入可能在条件为真时再次中断的内层循环。

If break appears in an inner loop of a nested loop construct, it abandons the inner loop and continues the iteration of the outer loop body. For the next iteration, it enters the inner loop again, which may be broken again if the condition is found to be true.

Example of break Statement with Nested for Loops

在以下程序中,使用两个嵌套循环来获取 1 到 30 之间所有质数的列表。当发现一个数字可以被整除时,内层循环会中断,并将标志设置为 1。内层循环之后,检查标志的值。如果是 “0”,则该数字是质数。

In the following program, two nested loops are employed to obtain a list of all the prime numbers between 1 to 30. The inner loop breaks out when a number is found to be divisible, setting the flag to 1. After the inner loop, the value of flag is checked. If it is "0", the number is a prime number.

#include <stdio.h>

int main(){
   int i, num, n, flag;
   printf("The prime numbers in between the range 1 to 30:\n");

   for(num = 2; num <= 30; num++){
      flag = 0;
      for(i = 2; i <= num/2; i++){
         if(num % i == 0){
            flag++;
            break;
         }
      }
      if(flag == 0)
         printf("%d is prime\n",num);
   }
   return 0;
}
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime

Break Statement in an Infinite Loop

无限循环极少被有意创建。但是,在某些情况下,你可能会启动一个 infinite loop 并在达到特定条件时中断它。

An infinite loop is rarely created intentionally. However, in some cases, you may start an infinite loop and break from it when a certain condition is reached.

Example of break Statement with Infinite Loop

在以下程序中,使用一个无限的 for 循环。在每次迭代中,在 1 到 100 之间生成一个随机数,直至获得一个可以被 5 整除的数字。

In the following program, an infinite for loop is used. On each iteration, a random number between 1 to 100 is generated till a number that is divisible by 5 is obtained.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(){
   int i, num;
   printf ("Program to get the random number from 1 to 100: \n");

   srand(time(NULL));

   for (; ; ){
      num = rand() % 100 + 1;   // random number between 1 to 100
      printf (" %d\n", num);

      if (num%5 == 0)
         break;

   }
}

运行这段代码后,你会得到如下所示的输出 −

On running this code, you will get an output like the one shown here −

Program to get the random number from 1 to 100:
6
56
42
90

Break Statements in Switch Case

为了将控制权移出 switch 范围,每个 case 块都以 break 语句结束。否则,程序会遍历所有 case 块,这是不希望看到的。

To transfer the control out of the switch scope, every case block ends with a break statement. If not, the program falls through all the case blocks, which is not desired.

Example of break Statement with switch

在以下代码中,一系列 if-else statements 根据 “ch” variable (“m”、“a”或 “e”表示早上、下午或晚上) 的值打印三个不同的问候信息。

In the following code, a series of if-else statements print three different greeting messages based on the value of a "ch" variable ("m", "a" or "e" for morning, afternoon or evening).

#include <stdio.h>

int main(){

   /* local variable definition */
   char ch = 'm';
   printf("Time code: %c\n\n", ch);

   switch(ch) {

      case 'm':
         printf("Good Morning \n");
         break;

      case 'a':
         printf("Good Afternoon \n");
         break;

      case 'e':
         printf("Good Evening \n");
         break;

      default:
         printf("Hello");
   }
}

在此处, break 语句在检查第一个 case 后中断了程序执行。

Here, the break statement breaks the program execution after checking the first case.

Time code: m

Good Morning

现在,注释 break 语句并再次运行代码。你现在将获得以下输出 −

Now, comment the break statements and run the code again. You will now get the following output −

Time code: m

Good Morning
Good Afternoon
Good Evening
Hello