ZetCode

C break

最后修改于 2023 年 1 月 9 日

C break 教程介绍了如何在 C 语言中终止 do、for、switch 或 while 语句。

break 语句

break 语句会终止其所在的最接近的 do、for、switch 或 while 语句的执行。

程序的执行将转到被终止语句之后的语句。

while 循环中的 C break

在下面的示例中,我们将 break 语句与 while 循环一起使用。通过 while (1),我们创建了一个无限循环。为了终止循环,我们使用了 break 语句。

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

int main() {

    srand(time(NULL));

    while (1) {

        int r = rand() % 30;

        printf("%d ", r);

        if (r == 22) {

            break;
        }
    }

    printf("\n");

    return 0;
}

该示例计算一个介于 0 到 29 之间的随机值。如果该值等于 22,则循环将通过 break 语句结束。

$ ./break_while
27 17 21 12 25 5 8 6 10 24 9 19 4 19 1 13 18 22

for 循环中的 C break

在下一个示例中,我们将 break 语句与 for 循环一起使用。通过 for(;;),我们创建了一个无限 for 循环,并使用 break 来终止它。

break_for.c
#include <stdio.h>

int main() {

   char c;

   for(;;) {

      printf("Press any key, q to quit: ");

      scanf(" %c", &c);
      printf("%c\n", c);

      if (c == 'q') {
          break;
      }
   }
}

该示例打印输入的字符,直到 'q' 字符终止程序。

$ ./break_for 
Press any key, q to quit: s
s
Press any key, q to quit: e
e
Press any key, q to quit: w
w
Press any key, q to quit: q
q
$

switch 语句中的 C break

在下面的示例中,我们将 break 语句与 switch 语句一起使用。

break_switch.c
#include <stdio.h>

int main() {

    printf("Are you sure to continue? y/n ");

    char c;

    scanf(" %c", &c);

    switch (c) {

        case 'y':

            printf("program continues\n");
            break;

        case 'n':

            printf("program stops\n");
            break;

        default:
            printf("wrong option\n");
    }
}

系统会询问我们是否要继续,并提供两个选项:y 或 n。

case 'y':

    printf("program continues\n");
break;

对于 'y',会执行一个特定的语句。然后,switch 语句会通过 break 终止,并且不再评估其他选项。

在本文中,我们介绍了 C break 语句。