温馨提示×

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

小樊
92
2024-07-06 00:48:20
栏目: 编程语言
C语言开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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语句的执行。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:C语言累乘在实际开发中的例子

0