c语言

C语言break语句在实际开发中的例子

小樊
84
2024-07-06 00:48:20
栏目: 编程语言

在C语言中,break语句通常用于中断循环或switch语句的执行,以下是一些在实际开发中使用break语句的例子:

  1. 中断循环:
#include <stdio.h>

int main() {
    int i;
    for (i = 1; i <= 10; i++) {
        if (i == 5) {
            break;
        }
        printf("%d ", i);
    }
    
    return 0;
}

输出结果为:1 2 3 4

  1. 中断switch语句:
#include <stdio.h>

int main() {
    int choice = 2;
    switch(choice) {
        case 1:
            printf("You chose option 1\n");
            break;
        case 2:
            printf("You chose option 2\n");
            break;
        case 3:
            printf("You chose option 3\n");
            break;
        default:
            printf("Invalid choice\n");
    }
    
    return 0;
}

输出结果为:You chose option 2

这些例子展示了在实际开发中如何使用break语句来中断循环或switch语句的执行。

0
看了该问题的人还看了