C++基础--if/else和switch/case的区别

if和switch的区别:

一、语句的格式:

  if/else的写法格式如下:

    int nA, nB;
    scanf_s("%d", &nA);  //输入整数并赋值给变量a
    scanf_s("%d", &nB);
    ("%d", &nB);  //输入整数并赋值给变量b
    if (nA > nB)
    {
        printf("%d greater than %d", nA, nB);
    }
    else
    {
        printf("%d smaller than %d", nA, nB);
    }

swith/case的写法如下:

    int nA, nB;
    scanf_s("%d", &nA);  //输入整数并赋值给变量a

    nB = nA + 1;
    switch (nA)
    {
    case 1:
        printf("when A is %d, B is", nA, nB);
    case 2:
        printf("when A is %d, B is", nA, nB);
    default:
        printf("when A is %d, B is", nA, nB);

    }

二、逻辑结构:

 从上面if/else与switch/case格式的区别可以看出:

  A: if/else能根据逻辑判断输出相应的语句,也就是说if/else更多的是进行逻辑判断;

      switch/case从某种角度上来说,没有相应的逻辑比较判断,而是根据给出项跳转到相应的分支;

  B: if判断相应的逻辑语句,返回true/false,每条if语句都会执行一次逻辑判断;

      switch/case会建立相应的跳转表,根据跳转表的项跳转到相应的分支。

三、效率

  从两种语句的判断上可以看出:

  A: 从某种程度上,Switch/case比if/else的效率要高,除非if/else在第一次逻辑判断就为true;

  B: Switch/case需要建立一张跳转表,因此需要一定的空间的,更像是以空间换效率。

  C: if/else能进行逻辑判断,而Switch不行,因此在需要进行逻辑判断时使用if/else语句;

四、支持的数据类型

  Switch/case只支持部分数据类型:int、long和枚举类型,由于byte、short、char都可以隐含转换为int,因此:switch支持的数据类型为:byte、short、char,int、long和枚举类型,不支持:boolean、float、double;

  if/else支持更多的数据类型,如String, double等;

建议:在能用Switch/case的情况下,尽量用Switch/case来提高效率;

原文地址:https://www.cnblogs.com/anlia/p/11685639.html