C语言中的逻辑选择语句

130 阅读1分钟

在 C语言 中,想要实现逻辑选择语句,拥有两种途径,if-else 多路选择分支,switch 语句。

我们可以从下面的案例中进行探究。

在这里插入图片描述

/*
    if_else.c
        if-else 多路选择结构
    BeginnerC
*/
#include <stdio.h>
int main()
{
    int choose;
    scanf("%d", &choose);
    if (1 == choose)
    {
        printf("You choose one.\n");
    }
    else if (2 == choose)
    {
        printf("You choose two.\n");
    }
    else
    {
        printf("You choose another.\n");
    }
    return 0;
}

而将这个简单的程序改写成 switch 语句,则可以变成如下的形式。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JRobTTk9-1683330519869)(https://foruda.gitee.com/images/1677919723270215167/bfd1e021_871414.png "1675379831912.png")]

/*
    switch.c
        使用 switch 进行多路判断
    BeginnerC
*/
#include <stdio.h>
int main()
{
    int choose;
    scanf("%d", &choose);
    switch (choose)
    {
        case 1:
        {
            printf("You choose one.\n");
            break;
        }
        case 2:
        {
            printf("You choose two.\n");
            break;
        }
        default:
        {
            printf("You choose another.\n");
            break;
        }
    }
    return 0;
}

相较于 if,switch 语句在 逻辑的选择判断上 有着更出色的性能与更良好的可读性。