多重if else和switch case的区别

int main(void)
{
    int id;
    scanf_s("%d",&id);

    switch(id)
    {
        case 2:
            printf("John\n");
            break;
        case 13:
            printf("Mary\n");
            break;
        case 16 :
            printf("Amy\n");
            break;
        default :
            printf("not found");
            break;
    }

    return 1;
}

switch case 当case是某个值的时候会直接把流程执行到那里,只进行一次判断。

而多重else if,else if的层次越深,需要判断的次数就越深。如果判断条件是比较复杂的,那么就会影响性能。

就上面那个switch case 用else if也能实现

int main(void)
{
    int id;
    scanf_s("%d",&id);

    if (id == 2)
    {
        printf("John");
    }
    else if(id==13){

        printf("Mary");
    }
    else if (id == 16)
    {
        printf("Amy");
    }
    else
    {
        printf("not found");
    }

    return 1;
}

如果用户输入的是0,那么需要经过id是否等于2这个判断,id是否等于13这个判断,id是否等于16这个判断,一共三个判断。

每次判断都是要耗费性能的,else if的层次越深 耗费的性能就越多。

总结:.switch...case只能处理case为常量的情况,对非常量的情况是无能为力的。例如 if (x > 1 && x < 100),是无法使用switch...case来处理的。所以,switch只能是在常量选择分支时比ifelse效率高,但是ifelse能应用于更多的场合,ifelse比较灵活。

参考: